混入mixin
- 什么叫做混入?
- 将组件的选项中的一部分分离出去,单独管理
- 方式有两种
- 局部混入 mixins 【 推荐 】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click = "aa"> 点击 </button>
<button @click = "bb"> 点击 </button>
</div>
</body>
<script src="../../lib/vue.js"></script>
<script src="./07-minxin.js"></script>
<script>
new Vue({
el: '#app',
mixins: [ obj ],
methods: {
bb () {
alert('bb')
},
aa () {
alert('cc')
}
}
})
</script>
</html>
//js代码
const obj = {
methods: {
aa () {
alert('aa')
}
}
}
- 全局混入 Vue.mixin 【 不推荐 】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click = "aa"> 点击 </button>
</div>
</body>
<script src="../../lib/vue.js"></script>
<script>
// Vue.mixin(选项)
Vue.mixin({
methods: {
aa () {
alert('aa')
}
}
})
new Vue({
el: '#app',
})
var vm = new Vue()
console.log( vm )
</script>
</html>
自定义插件
-
定义的插件应该有一个 install 方法
-
自定义插件必须使用 Vue.use( 插件名称 ) 才能使用插件
-
案例:
-
自定义Loading
-
封装组件库
-
vue路由
-
vue状态管理 vuex
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-focus>
<Hello></Hello>
</div>
</body>
<script src="../../lib/vue.js"></script>
<script src="./10-自定义插件.js"></script>
<script>
Vue.use( MyPlugin ) //使用插件
new Vue({
el: '#app'
})
</script>
</html>
//js代码
const MyPlugin = {
install ( Vue, options ) {
Vue.directive('focus',{
inserted ( el ) {
el.focus()
el.style.background = 'red'
}
})
Vue.component('Hello',{
template: '<div> hello </div>'
})
}
}