一、$nextTick()瞳氓、$forceUpdate()方法
<template>
<input type="text" v-model="carName" />
<button @click="addCar">添加汽車</button>
<ul ref="list">
<li v-for="item in cars" :key="item.id">
<input type="text" :value="item.name" />
</li>
</ul>
<hr />
<div>
<button @click="employe.name='蔡依林'">修改姓名</button>
<button @click="addSex">添加性別</button>
<div>{{ employe.name }}---{{ employe.age }}</div>
</div>
</template>
<script>
methods: {
addCar() {
let car = {
id: Date.now(),
name: this.carName,
};
this.cars.push(car);
this.carName = "";
// $nextTick方法策彤,需要傳一個(gè)回調(diào)函數(shù)
// 回調(diào)函數(shù)里面的代碼在DOM更新完成后執(zhí)行
this.$nextTick(() => {
// 讓最后一個(gè)li元素獲取焦點(diǎn)
this.$refs.list.lastChild.lastChild.focus();
});
},
addSex() {
// this.$set(this.employe,'sex','男')
this.employe.sex = "男";
this.$forceUpdate();
console.log(this.employe);
},
},
</script>
二、局部自定義指令
<template>
<div class="two">
<div v-red>好好學(xué)習(xí)</div>
<div v-html="car" v-color="'blue'"></div>
<div v-myhtml="car" v-color="'green'"></div>
</div>
</template>
<script>
export default {
name: "Two",
//定義局部指令匣摘,所有的指令背后都是在操作DOM店诗,稱之為:造輪子
//自定義局部指令,就是一個(gè)方法,有個(gè)參數(shù)叫el,就是這個(gè)指令所在的DOM元素音榜,就是這個(gè)div
directives: {
red: function (el) {
el.style.color = "red";
},
//指令方法的第二個(gè)參數(shù)庞瘸,是指令的值,可寫可不寫囊咏,也可自定義
myhtml: function (el, bind) {
el.innerHTML = bind.value;
},
},
data() {
return {
car: "<h2>瑪莎拉蒂</h2>",
};
},
};
</script>
三恕洲、全局自定義指令
// 創(chuàng)建全局自定義指令
// 1、directive文件夾的index文件中先引入vue
import Vue from 'vue'
//color是自定義指令的名字梅割,使用的時(shí)候前面加上v-
Vue.directive('color',function(el,bind){
//自定義局部指令,就是一個(gè)方法霜第,有個(gè)參數(shù)叫el,就是這個(gè)指令所在的DOM元素,就是這個(gè)div
//指令方法的第二個(gè)參數(shù)户辞,是給指令綁定的值泌类,可寫可不寫,bind也可自定義
el.style.color=bind.value
})
2、然后去main.js中去注冊(cè)
import index from './directive/index'
3刃榨、使用 v-color=" 'green' " "green"是變量 "'green'"是表達(dá)式弹砚,要加上單引號(hào)
<div v-myhtml="car" v-color="'green'"></div>
四、自定義插件
<button @click="sayHello">sayhello</button> |
<button @click="showPlane">showPlane</button>
<div v-bgcolor="'lightblue'">我是背景色</div>
混入只能寫數(shù)據(jù)枢希、方法和生命周期桌吃,插件的功能比混入更為強(qiáng)大,插件是擴(kuò)展vue的功能
//插件本質(zhì)上是一個(gè)對(duì)象
export default {
// 該對(duì)象中必須包含install()方法
// install()方法第一個(gè)參數(shù)是Vue,第二個(gè)是配置對(duì)象
//install()方法會(huì)在use的時(shí)候執(zhí)行vue.use(插件)苞轿,這里的vue會(huì)作為install方法的第一個(gè)對(duì)象
install: function (Vue, options) {
// 可以給vue直接添加方法
Vue.sayHi = function () {
console.log('大家好茅诱,我是vue');
},
//可以添加屬性
Vue.msg="歡迎使用插件",
// 可以在vue的原型上添加方法
Vue.prototype.sayHello = function () {
console.log('我是vue原型上的方法');
},
Vue.mixin({ //混入只能寫數(shù)據(jù) 方法 和生命周期
data() {
return {
plane:{
name:'波音747',
price:'1000w'
}
}
},
methods: {
showPlane(){
console.log(this.plane.name,this.plane.price);
}
},
}),
// 注冊(cè)全局組件
Vue.component('b-box',{
render(h) {
return h('div',this.$slots.default)
},
}),
// 注冊(cè)全局指令
Vue.directive('bgcolor',function(el,bind){
el.style.backgroundColor=bind.value
})
}
}
2、在main.js 里面導(dǎo)入
import myPlugin from './plugins'
Vue.use(myPlugin)