自定义指令
directives局部自定义指令语法
规则
- 定义指令名称不能使用驼峰和v-,要是用-连接,记得添加引号
- 使用时要v-自定义名称
函数写法
- 名称(节点,绑定对象){ }
对象写法
名称:{
绑定成功调用
bind(节点,绑定对象){},
插入到页面调用
inserted(节点,绑定对象){},
重新解析时调用(值发生改变)
update(节点,绑定对象){}
}
<body>
<div id="app">
<button @click="func()">点击</button>
<h1 v-nums="sum"></h1>
<h1 v-nums-ing="sums"></h1>
<h1 v-num1="sum1"></h1>
<h1 v-num2="sum2"></h1>
</div>
</body>
<script src="../vue.js"></script>
<script>
Vue.config.productionTip = false;
var vm = new Vue({
el:"#app",
data() {
return {
sum:0,
sums:1,
sum1:0,
sum2:1,
}
},
directives:{
"nums-ing"(element,binding){
element.innerHTML = binding.value+100;
},
"nums":{
// bind成功绑定时调用
bind(element,binding){
},
// inserted成功插入页面调用
inserted(element,binding){
element.innerHTML = binding.value+100;
binding.value = binding.value+100;
},
// update重新解析时(改变)调用
update(element,binding){
element.innerHTML = binding.value+binding.oldValue;
binding.value = binding.oldValue;
}
}
},
methods: {
func(){
this.sum++;
this.sums++;
this.sum1 += 2;
if(this.sum2%2==1){
this.sum2 += 2;
}else{
this.sum2 += 1;
}
}
},
})
</script>
1.局部自定义指令
directives ,写入Vue实例中
2.全局自定义指令
Vue.directive ,定义在实例化之前
<body>
<div id="app">
<input type="text" v-model="a">
<input type="text" v-model="b">
<!-- 1.使用插值做计算 -->
<h1>{{a-b}}</h1>
<h1>{{a}}-{{b}}</h1>
<!-- 2.methods操作计算 -->
<h1>{{func()}}</h1>
</div>
</body>
<script src="../vue.js"></script>
<script>
Vue.config.productionTip = false;
var vm = new Vue({
el:"#app",
data() {
return {
a:0,
b:0,
}
},
fullNames:{
get(){
return this.a-this.b;
return 199;
},
set(value){
console.log(value);
console.log("触发了set");
}
},
fullName(){
console.log("简写的计算方法触发了");
return 99;
}
},
methods: {
func(){
return this.a+"-"+this.b
},
},
})
</script>
Vue的MVVM模型,数据代理
MVVM与MVC区别
- VM(vue)==C(调服务)
- MVVM双向(双向绑定,数据代理),MVC单向(直接操作DOM)
- MVVM(虚拟DOM)更快渲染,MVC单向(真实DOM)
<body>
<div id="app">
<input type="text" v-model="a">
<input type="text" v-model="b">
<select name="" id="" v-model="num">
<option v-for="(item,index) of arr" :value="index" :key="index+item">{{item}}</option>
<!-- <option value="0">江西</option>
<option value="1">湖南</option>
<option value="2">广东</option> -->
</select>
<select name="" id="">
<option v-for="(item,index) of arrs[num]" :key="item+index" value="index">{{item}}</option>
</select>
</div>
</body>
<script src="../vue.js"></script>
<script>
Vue.config.productionTip = false;
var vm = new Vue({
el:"#app",
data() {
return {
a:0,
num:"1",
b:0,
arr:["江西","湖南","广东"],
arrs:[
["南昌","吉安","抚州","赣州"],
["长沙","株洲","怀化","岳阳"],
["广州","深圳","佛山","潮汕"]
]
}
},
let obj = {
name:"张三",
age:18,
sex:"男"
}
obj.sclNum = 202201;
obj["a"] = 110;
Object.defineProperty(obj,"b",{
value:10,
enumerable:true, // 可循环
writable:true, // 可修改
configurable:true, // 可删除
get(){
console.log("触发了get方法");
return 10;
},
set(value){
console.log(value);
console.log("触发了set方法");
}
});
console.log(obj.b);
obj.b = 20;
console.log(obj);
</script>