Vue的基础常用指令
v-bind
:Vue实例的选项属性向DOM属性的单向绑定;v-if
:根据Vue实例的选项属性是否显示该DOM结构;v-for
:根据Vue实例的选项属性渲染该项目列表;v-on
:绑定一个事件监听器;v-model
:Vue实例的选项属性与DOM属性的双向绑定;
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
<script src="D:\myDownload\vue.js"></script>
</head>
<body>
<div id="testVue">
<span v-bind:title='ATTRMessage' v-if='seen'>
{{HTMLMessage}}
<ol>
<li v-for="item in items">
{{item.text}}
</li>
</ol>
<label>update message on html sync:</label>
<input v-model="HTMLMessage">
</span>
<br>
<button v-on:click='upperCase'>upperCase</button>
<button v-on:click='toggleShow'>toggleShow</button>
</div>
</body>
<script>
new Vue({
el:'#testVue',
data:{
HTMLMessage:'message on html',
ATTRMessage:'message on attribute',
seen:true,
items:[
{text:'a'},
{text:'b'},
{text:'c'}
]
},
methods:{
upperCase:function(){
for(item of this.items){
item.text=item.text.toUpperCase();
}
},
toggleShow:function(){
this.seen=this.seen?false:true;
}
}
});
</script>
</html>
Vue组件
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
<script src="D:\myDownload\vue.js"></script>
</head>
<body>
<div id="testVue">
<my-compute v-on:minus="minus" v-on:plus="plus" v-bind='object'>
<h1 slot="header">START</h1>
<label>num1</label>
<input v-model.number='object.num1' type="number">
<br>
<label>num2</label>
<input v-model.number='object.num2' type="number">
<br>
<h1 slot="footer">END</h1>
</my-compute>
</div>
</body>
<script>
Vue.component('my-compute',{
props:{
num1:Number,
num2:Number,
operation:String
},
data:function(){
return {
str:'generate expression from data:'
}
},
template:'<div>\
<slot name="header"></slot>\
<slot></slot>\
<p>{{str}}{{num1}}{{operation}}{{num2}}={{result}}</p>\
<button v-on:click="plus">plus</button>\
<button v-on:click="minus">minus</button>\
<slot name="footer"></slot>\
</div>',
computed:{
result:function(){
if(this.operation=="+"){
return this.num1+this.num2;
}
if(this.operation=="-"){
return this.num1-this.num2;
}
}
},
methods:{
plus:function(){
console.log("run plus function from child");
this.$emit('plus');
},
minus:function(){
console.log("run minus function from child");
this.$emit('minus');
}
}
});
var vm=new Vue({
el:'#testVue',
data:{
object:{
num1:0,
num2:0,
operation:"+"
}
},
methods:{
minus:function(){
console.log("run minus function from parent");
this.object.operation="-";
},
plus:function(){
console.log("run plus function from parent");
this.object.operation="+";
}
}
});
</script>
</html>