Introduction to Vue Plugins (Plugin), Dynamic Components (Component) and Mixins (mixin)

Table of contents

1. Plug-ins

2. Dynamic components

keep-alive

The life cycle of dynamic components

Three, mixed in 


1. Plug-ins

Plugins are often used to add global functionality to Vue. Vue.js plugins should expose an install method. The first parameter of this method is the Vue constructor, and the second parameter is an optional options object.

Plugins are used via the global method Vue.use().

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
</head>
<body>
	<div id="app">
    <!-- 使用插件中的过滤器 -->
    {
   
   {new Date().getTime() | fmtDate}}
    <!-- 使用插件中定义的自定义指令 -->
    <input type="text" v-focus>
  </div>
	<script>
    // 1.定义一个插件
    let myPlugin = {
      // 插件暴露一个install方法 参数:Vue构造函数 option可选项
      install(Vue,options){
        // 1.1 定义全局资源 Vue.xxx
        //定义一个 自定义指令
        Vue.directive('focus',{
          inserted(el){
            el.focus()
          }
        });
        //定义一个过滤器
        Vue.filter('fmtDate', function(val){
          return moment(val).format('YYYY-MM-DD')
        });
        //1.2 定义一个实例方法,定义在Vue的原型上 Vue.prototype.xxx
        Vue.prototype.message = function(val){
          console.log(val);
        }
      }
    }

    //2.使用插件
    Vue.use(myPlugin)
    
	new Vue({
		el:"#app",
		created(){
            // 插件中在Vue原型上定义了一个方法message,因此这里可以使用message方法
            this.message('请求成功!')
        }
	})
    </script>
</body>
</html>

2. Dynamic components

Dynamic components use the component tag, and use v-bind to bind the is attribute in the tag to dynamically switch components:

<component :is="current"></component>

Example:
Click the corresponding button to switch the corresponding component:

<body>
	<div id="app">
    <button @click="current=myA">切换A组件</button>
    <button @click="current=myB">切换B组件</button>
    <component :is="current"></component>
  </div>
	<script>
    // 定义组件myA
    let myA = {
      template:`
        <div>我是A组件</div>
      `
    }
    // 定义组件myB
    let myB = {
      template:`
        <div>我是B组件</div>
      `
    }
	new Vue({
		el:"#app",
		// 注册组件
        components:{
            'my-a': myA,
            'my-b': myB
        },
        data:{
            current: myA
        }
	})
	</script>
</body>

keep-alive

 By default, components are recreated when they are switched, but sometimes we want component instances to be cached when they are first created. To solve this problem, we can wrap its dynamic components with a <keep-alive> element.

<keep-alive>
   <component :is="current"></component> 
</keep-alive>

The life cycle of dynamic components

Three new life cycles have been added to dynamic components:

activated: enter the activation component

deactivated: left deactivated

errorCaptured: An error capture error occurred in the child component/descendant component

Trigger sequence:

created-->errorCaptured-->mounted-->activated-->deactivated

<body>
	<div id="app">
    <button @click="current=myA">切换A组件</button>
    <button @click="current=myB">切换B组件</button>
    <keep-alive>
      <component :is="current"></component> 
    </keep-alive>
  </div>
	<script>
    // 定义一个A的子组件,用来说明errorCaptured声明周期
    let aChild={
			template:`
				<div>
					A组件的子组件
					{
   
   {subMsg}}
				</div>
			`
		};
    // 定义组件myA
    let myA = {
      template:`
        <div>我是A组件
          <a-child></a-child>
        </div>
      `,
      components:{
				'a-child': aChild
			},
      created(){
        alert('实例A初始化完成');
      },
      mounted(){
        alert('实例A挂载到页面完成')
      },
      // 激活组件 进入组件就会触发的生命周期
      activated() {
        alert('进入A组件了')
      },
      // 捕获子组件/后代组件发生错误的生命周期
	  errorCaptured(){
		alert('子组件发生错误了');
	  },
	  // 离开当前组件触发 停用组件
	  deactivated(){
		alert('离开A组件了');
	  },
    }
    // 定义组件myB
    let myB = {
      template:`
        <div>我是B组件</div>
      `
    }
	new Vue({
		el:"#app",
		// 注册组件
        components:{
            'my-a': myA,
            'my-b': myB
        },
        data:{
            current: myA
        }
	})
	</script>
</body>

Three, mixed in 

Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain arbitrary component options. When a component uses a mixin, all of the mixin's options will be "mixed in" into the component's own options.

global mixins

Vue. mixin()

It is not recommended to use the global registration mix-in object, once the global mix-in is used, it will affect every vue instance created in the future.

Partial mix-in

Use the mixin configuration item mixins:[] in the component instance

mix-in rules

When components and mixins have options with the same name, those options are merged appropriately:

1. Data data:

When the data object is mixed in, it will be merged, and when a conflict occurs, the data of the component will be retained

2. The value is the object methods, computed, etc.:

When mixing in, methods will be merged into one object. If the key name of the object conflicts, the key-value pair of the component object will be retained

3. Life cycle hook function:

Hook functions with the same name will be merged into an array and will be called sequentially, but the hook function mixed into the object will be called first

<body>
	<div id="app">
    {
   
   {mixinMsg}}
	{
   
   {foo()}}
	{
   
   {bar()}}
  </div>
	<script>
    // 定义一个混入对象
    let myMixin = {
      data(){
        return{
          mixinMsg: '我是混入对象的数据',
          age: 18
        }
      },
      created(){
        console.log('我是混入的生命周期');
      },
      methods:{
        foo(){
          return this.age
        },
        bar(){
          console.log('我是混入方法');
        }
      },
    }
    // 全局混入——>混入到所有组件实例
    // Vue.mixin(myMixin);
	new Vue({
      // 局部混入
      mixins: [myMixin],
	  el:"#app",
      // 数据对象在混入时,会进行合并,发生冲突时,保留组件的数据
	  data:{
		msg: '我是vue实例的数据模型',
        age: 20
	  },
      // 生命周期会合并并依次调用执行 混入的生命周期优先执行
      created(){
		console.log('我是组件的生命周期');
		console.log(this.$data);
      },
      // 在混入时,methods会合并成为一个对象,如果对象的键名发生冲突,则保留组件对象的键值对
	  methods:{
        bar(){
          console.log('我是组件的方法');
        }
      }
	})
	</script>
</body>

 

Guess you like

Origin blog.csdn.net/lq313131/article/details/127091684