今天是2022年7月2日,是我学习vue的第十三天
今天可能学的比较少
插件
-
功能:用于增强Vue
-
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
-
定义插件:
对象.install = function (Vue, options) {
// 1. 添加全局过滤器
Vue.filter(....)
// 2. 添加全局指令
Vue.directive(....)
// 3. 配置全局混入(合)
Vue.mixin(....)
// 4. 添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxxx
}
例如:
plugins.js
export default {
install(Vue) {
//全局过滤器
Vue.filter('mySlice', function (value) {
//过滤字符
return value.slice(0, 4)
})
// 定义全局指令
Vue.directive('fbind', {
// 指令与元素成功绑定时(一上来)执行
bind(element, binding) {
// console.log(this); //注意:此处的this是Window ,directives自定义指令的this都是指向Window
element.value = binding.value
console.log('@element', element);
console.log('@binding', binding);
},
// 指令所在的元素被插入页面时执行
inserted(element, binding) {
// 获取焦点
element.focus()
},
// 指定所在的模板被重新解析时执行
update(element, binding) {
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data() {
return {
x: 100,
y: 999,
}
}
})
//给Vue原型上添加一个方法,vm和vc都能用
Vue.prototype.hello = () => {
alert('你好啊!')
};
}
}
SchoolTest.vue
<template>
<div class="demo">
<h2>学校名称:{{ schoolName |mySlice }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="test">点我测试hello方法</button>
</div>
</template>
<script>
export default {
name: "SchoolTest",
data() {
return {
schoolName: "尚硅谷giao",
address: "北京",
};
},
methods: {
test() {
this.hello()
}
}
};
// export default school
</script>
<style>
</style>
- 使用插件:
Vue.use()
main.js
// 该文件是整个项目的入口文件
//引入vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//引入插件
import plugins from './plugins'
//关闭vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(plugins)
//创建vue的实例对象——vm
new Vue({
//将App组件放入容器中
// render: h => h(App),
render(h) {
return h(App)
},
}).$mount('#app') // 就是el:'#app'
scoped样式
- 作用:让样式在局部生效,防止冲突。
- 写法:
<style scoped>
<template>
<div class="demo">
<h2>学校名称:{{ schoolName |mySlice }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name: "SchoolTest",
data() {
return {
schoolName: "尚硅谷giao",
address: "北京",
};
},
};
// export default school
</script>
<style scoped>
.demo{
background-color: pink;
}
</style>
StudentTest.vue
<template>
<div class="demo">
<h2>学校名称:{{ schoolName |mySlice }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name: "SchoolTest",
data() {
return {
schoolName: "尚硅谷giao",
address: "北京",
};
},
};
// export default school
</script>
<style scoped>
.demo{
background-color: pink;
}
</style>