自定义全局插件 组件

官网地址:https://cn.vuejs.org/v2/guide/plugins.html

使用指令创建项目:

运行项目,看项目能否正常运行:

 运行结果说明项目能正常运行:

在官网中有这样的部分:

在生成的项目中新建该目录:

 myButton.vue

 1 <template>
 2     <div class="mybtn">
 3         
 4         <button>{{name}}</button>
 5     </div>
 6 </template>
 7 
 8 <script>
 9     export default{
10     data(){
11         return{
12             name:this.btnName
13         }
14     },
15     props:{
16         btnName:{
17             type:String,
18             default:'确认'
19             
20             
21         }
22         
23         
24     }
25     }
26 </script>
27 
28 <style>
29 button{
30     
31     150px ;
32     height: 35px;
33     font-size: 18px;
34     font-weight: 700;
35     color: rgb(53,73,93);
36     background-color: rgb(65,184,131);
37 }
38 </style>

myButton.js

import mybtn from './myButton.vue'


export default{
    
    install:function(Vue){
        
        Vue.component('mybtn',mybtn);
        
    }
}

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import mybtn from './custom/myButton.js'



Vue.use(mybtn)

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

About.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <mybtn btnName="about Button"></mybtn>
  </div>
</template>

Home.vue

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <mybtn btnName="about Button"></mybtn>
  </div>
</template>

<script>



export default {
  name: "home",
 
};
</script>

从效果图中看出问题:

 问题描述:点击button的时候没有发生任何改变

解决问题方法:

Home.vue

在button中加入一个click事件:

 1 <template>
 2   <div class="home">
 3     <img alt="Vue logo" src="../assets/logo.png" />
 4     <h1>{{msg}}</h1>
 5     <mybtn btnName="about Button" @click.native="changeName"></mybtn>
 6   </div>
 7 </template>
 8 
 9 <script>
10 
11 
12 
13 export default {
14   name: "home",
15  methods:{
16      changeName(){
17          this.msg="home"
18      }
19  },
20  data(){
21      return{
22          msg:"欢迎来到perfect*博客园"
23      }
24  }
25  
26 };
27 </script>
加入监听事件

其中    .native 监听组件根元素的原生事件

实现的效果:

原文地址:https://www.cnblogs.com/jiguiyan/p/11593577.html