Vue常见指令
Vue常见的内置指令
- v-text : 更新元素的 textContent
- v-html : 更新元素的 innerHTML
- v-if : 如果为 true, 当前标签才会输出到页面
- v-else: 如果为 false, 当前标签才会输出到页面
- v-show : 通过控制 display 样式来控制显示/隐藏
- v-for : 遍历数组/对象
- v-on : 绑定事件监听, 一般简写为@
- v-bind : 强制绑定解析表达式, 可以省略 v-bind
- v-model : 双向数据绑定
- ref : 指定唯一标识, vue 对象通过$els 属性访问这个元素对象
- v-cloak : 防止闪现, 与 css 配合: [v-cloak] { display: none }
简单的代码演示如下:
<div id="demo">
<p ref='content'>baidu.com</p>
<button @click="hint">提示</button>
<p v-text="msg"></p>
<p v-cloak>{{msg}}</p>
</div>
<script src="../js/vue.min.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
msg: '你好啊'
},
methods: {
hint: function(){
alert(this.$refs.content.textContent);
}
}
})
</script>
v-model : 双向数据绑定指令
使用 v-model 对表单数据自动收集
1) text/textarea
2) checkbox
3) radio
4) select
见如下代码:
<div id="demo">
<form action="/xxx" @submit.prevent="handSubmit">
<span>用户名:</span>
<input type="text" v-model="username" /><br/>
<span>密码:</span>
<input type="password" v-model="pwd" /><br/>
<span>性别:</span>
<input type="radio" id="female" value="女" v-model="sex" />
<label for="female">女</label>
<input type="radio" id="male" value="男" v-model="sex" />
<label for="male">男</label><br/>
<span>爱好:</span>
<input type="checkbox" id="basket" value="篮球" v-model="likes" />
<label for="basket">篮球</label>
<input type="checkbox" id="foot" value="足球" v-model="likes" />
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" value="乒乓球" v-model="likes" />
<label for="pingpang">乒乓球</label><br/>
<span>城市:</span>
<select v-model="cityId">
<option value="">未选择</option>
<option :value="city.id"
v-for="(city,index) in allCitys" :key='index'>{{city.name}}</option>
</select><br/>
<span> 介绍:</span>
<textarea rows="10" v-model="desc"></textarea><br/>
<input type="submit" value="注册" />
</form>
</div>
<script src="../js/vue.min.js"></script>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
username: '',
pwd: '',
sex: '女',
likes: ['足球'],
allCitys: [{
id: 1,
name: 'BJ'
},
{
id: 2,
name: 'TJ'
},
{
id: 3,
name: 'HB'
}
],
cityId: '2',
desc: ''
},
methods: {
handSubmit: function() {
console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.desc);
}
}
})
</script>
效果如下: