插件
功能:用于增强vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个及以后的参数是插件使用者传递的参数。install(Vue,x,y,z)
plugins.js:
// 1.定义插件
export default{
install(Vue){
// 添加全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4) //截取前四位
}),
// 添加全局指令(自定义指令),细分:
// Vue.directive("fbind",{
// // 指令与元素重新绑定时
// bind(element,binding){
// element.innerText=binding.value
// },
// // 指令所在元素被插入页面时
// inserted(element,binding){
// element.focus()
// },
// // 指令所在的模板被重新解析时
// update(element,binding){
// element.innerText=binding.value
// },
// 添加全局指令(自定义指令)
Vue.directive("big",function(element,binding){
element.innerText=binding.value*10
})
// }),
// 给Vue原型上添加一个方法
Vue.prototype.hello=()=>{alert("你好啊")}
}
}
// 2.在main.js中引入插件并应用插件
main.js:
// 2.在main.js中引入插件
import plugins from './plugins'
Vue.config.productionTip = false
// 3.应用插件
Vue.use(plugins)
使用插件:
<!-- 运用插件中的全局过滤器 -->
<h1>{{msg | mySlice}}</h1>
<!-- 使用定义的插件 (自定义指令)-->
<h2>放大10倍n值是:<span v-big="n"></span></h2>
<!-- 使用 插件中Vue原型上添加的方法-->
<button @click="test">点我测试方法</button>
</div>
</template>
<script>
export default {
name:"SchoolInfo",
data(){
return {
msg:"欢迎学习Vue",
n:1
}
},
methods:{
test(){
this.hello() //注意写法
}
}
}
scoped
在SchoolInfo组件中,样式为:
在StudentInfo组件中,样式为:
此时,页面中盒子的颜色取决于App.vue中两个组件的引用顺序,App.vue代码:
先引入SchoolInfo,后引入StudentInfo,所以页面是StudentInfo组件中设置的样式。
但若在加上scoped,就只会使样式在对应的局部生效,用法:<style scoped>
StudentInfo组件:
<style scoped>
.demo {
background-color:skyblue;
}
</style>
SchoolInfo组件:
<style scoped>
.demo {
background-color: orange;
}
</style>
运行结果:
ps: App.vue中一般不加scoped
组件化编码流程
案例效果图:
使用组件实现静态页面效果
- 先分析效果图,对效果图进行划分组件,并确定组件名称
- 在对应位置创建好组建的基本框架,并修改name配置项中组件的名字
- 做好导入导出等一系列准备事项
- 将给定的结构和样式的代码全部复制到App.vue文件中对应位置。
- 在App.vue中对复制的内容进行理解或根据注释剪切到各个组件对应的位置,在App.vue文件中剪切的同时要把所对应的组件标签写在对应App.vue文件对应位置,以免最后混淆。
展示动态数据
要求实现下图区域的效果:
这一部分在MyList组件中,但每一条数据在MyItem组件中。MyItem是MyList的子组件
MyList.vue:
<!-- 遍历todos数组,要用多少次MyItem;并且要将每一条todoobj对应属性传给MyItem(用props) -->
<MyItem v-for="todoobj in todos" :key="todoobj.id" :todo="todoobj"/>
data(){
return {
todos:[
{id:"001",title:"打代码",done:"true"}, //id一般用字符串,done表示完成
{id:"002",title:"睡觉",done:"true"},
{id:"003",title:"吃饭",done:"true"}
]
}
MyItem.vue:
<template>
<li>
<label>
<input type="checkbox">
<span>{{todo.title}}</span>
<!-- 2.插值语法,对应需要的值 -->
</label>
<button class="btn btn-danger" style="display:none">删除</button>
</li>
</template>
<script>
export default {
name:"MyItem",
// 1.接受来自MyList组件传来的信息
props:["todo"]
}
</script>