Ajax
使用 vue-resource 库。
<script src="https://cdn.bootcss.com/vue-resource/1.5.1/vue-resource.min.js"></script>
get请求
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
get:function(){
//发送get请求,参数必须要用params包一下
this.$http.get('/try/ajax/ajax_info.txt',{params:{a:1,b:2}}).then(function(res){
document.write(res.body);
},function(){
console.log('请求失败处理');
});
}
}
});
post 请求
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
post:function(){
//发送 post 请求,参数不用包
this.$http.post('/try/ajax/demo_test_post.php',{name:"菜鸟教程",url:"http://www.runoob.com"},{emulateJSON:true}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});
}
}
});
复选框的全选功能
<div id="app">
<p>全选:</p>
<input type="checkbox" id="checkbox" v-model="checked" @change="changeAllChecked()">
<label for="checkbox">{{checked}}</label>
<p>多个复选框:</p>
<input type="checkbox" id="runoob" value="Runoob" v-model="checkedNames">
<label for="runoob">Runoob</label>
<input type="checkbox" id="google" value="Google" v-model="checkedNames">
<label for="google">Google</label>
<input type="checkbox" id="taobao" value="Taobao" v-model="checkedNames">
<label for="taobao">taobao</label>
<br>
<span>选择的值为:{{checkedNames}}</span>
</div>
对控件变化做监听,但是不能两都写成监听,否则值改变时多次相互触发
new Vue({
el: '#app',
data: {
checked: false,
checkedNames: [],
checkedArr: ["Runoob", "Taobao", "Google"]
},
methods: {
//不能两都写成监听,否则值改变时多次相互触发
changeAllChecked: function() {
if (this.checked) {
this.checkedNames = this.checkedArr
} else {
this.checkedNames = []
}
}
},
watch: {
"checkedNames": function() {
if (this.checkedNames.length == this.checkedArr.length) {
this.checked = true
} else {
this.checked = false
}
}
}
})
创建实列时调用函数
想在创造Vue后紧接着调用函数时可以将函数放到mounted中
new Vue({
el: '#mydiv',
mounted:function() {
alert('123');
}
});
组件data
对于template中使用到的变量需要在data中声明或者prop传递,
如果在data中声明时,data 必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
});
new Vue({ el: '#components-demo' });
解析dom模板时的注意事项
有些元素直接加模板会出错,原因:
有些 HTML 元素,诸如 <ul>、<ol>、<table> 和 <select>,对于哪些元素可以出现在其内部是有严格限制的。
而有些元素,诸如 <li>、<tr> 和 <option>,只能出现在其它某些特定的元素内部。
例如:
<table>
<blog-post-row></blog-post-row>
</table>
这个自定义组件 <blog-post-row> 会被作为无效的内容提升到外部,并导致最终渲染结果出错。幸好这个特殊的 is 特性给了我们一个变通的办法:
<table>
<tr is="blog-post-row"></tr>
</table>