Vue 动态组件components和v-once指令的实现

2019-11-09,,,

一、实现两个组件间互相展示、互相隐藏

<!DOCTYPE html>
<html>
<head>
  <title>动态组件</title>
  <script type="text/javascript" src="./vue-dev.js"></script>
</head>
<body>
  <div id="app">
    <child-one v-if="type=='child-one'" content="child-one"></child-one>
    <child-two v-if="type=='child-two'" content="child-two"></child-two>
    <button @click="handleChangeEvent">change</button>
  </div>
  <script type="text/javascript">
  Vue.component('child-one', {
    props: ["content"],
    template: `<div>{{content}}</div>`,
  });

   Vue.component('child-two', {
    props: ["content"],
    template: `<div>{{content}}</div>`,
  })

  var vm = new Vue({
    el: '#app',
    data(){
    	return{
    		type:'child-one'
    	}
    },
    methods:{
    	handleChangeEvent:function(){
    		this.type= this.type=="child-one" ? 'child-two':'child-one';
    	}
    }

  })
  </script>
</body>
</html>

页面效果图如下:

 

二、动态组件,简化页面代码

使用:父组件 dom标签使用 ,对组件名称进行绑定

 <div id="app">
    <!-- <child-one v-if="type=='child-one'" content="child-one"></child-one>
    <child-two v-if="type=='child-two'" content="child-two"></child-two> -->

     <!--动态组件标签component 利用is接收指定标签组件-->
    <component :is="type" :content="type"></component>
    <button @click="handleChangeEvent">change</button>
  </div>

无论使用v-if还是components来使用动态组件的实现,都是在点击交互后,每一次页面效果的切换,会自动销毁前一个组件,再重新创建一个组件,页面则显示响应的内容, 这样的实现方式是比较消耗性能的

三、 v-show和v-once

使用v-show,则会只是隐藏在dom元素中,组件都会被创建。

在子组件中,加入v-once,当每次切换组件效果时,不再需要每次都经过创建-销毁的过程,而是在内存中直接取用上一次使用过的组件的内容

 Vue.component('child-one',{
    template:'<div v-once>child-one</div>'
  })

  Vue.component('child-two',{
    template:'<div v-once>child-two</div>'
  })

使用v-once,可以有效提高静态内容的展示效率,提高性能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • Vue指令之 v-cloak、v-text、v-html实例详解
  • vue学习笔记之指令v-text && v-html && v-bind详解
  • vue 插值 v-once,v-text, v-html详解
  • vue2 v-model/v-text 中使用过滤器的方法示例
  • vue中v-text / v-html使用实例代码详解
  • vue防止花括号{{}}闪烁v-text和v-html、v-cloak用法示例
  • Vue 自定义指令功能完整实例
  • Vue 利用指令实现禁止反复发送请求的两种方法
  • vue使用自定义指令实现拖拽
  • Vue入门学习笔记【基本概念、对象、过滤器、指令等】
  • Vue v-text指令简单使用方法示例

《Vue 动态组件components和v-once指令的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。