1、VUE的生命周期中钩子函数中this是undefined
在created、mounted、updated等等钩子函数中出现以下情况。
mounted: () => {
console.log(this); // "undefined"
},
computed: {
foo: () => {
console.log(this); // "undefined"
}
} 在官方文档有提到,不要对实例属性或回调函数使用箭头函数,使用箭头函数拿到的this并不是VUE实例且为undefined。使用常规函数才能得到。
mounted: function () {
console.log(this);
} 2、同时使用VUE和JQUERY
想同时在一个页面上使用VUE和JQUERY就需要将两者管理的做好选择,要么JQUERY来操作DOM要么VUE来操作DOM,不能两者同时操作。在内容需要更改时,使用VUE组件进行中间协商,VUE可以通过组件事件来调用JQUERY进行更新,JQUER监听DOM事件,然后通过组件事件通知VUE。
3、子组件更父组件传递的数据
//html
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter> //监听子组件increment事件
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
//子组件
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1;
this.$emit('increment');//抛出子组件事件increment通知父组件更新数据
}
},
})
//父组件
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1;//子组件事件触发,父组件更新数据total
}
}
}) 4、在vuex的actions中返回异步函数
vuex的actions提交的是 mutation,而不是直接变更状态,可以包含任意异步操作。能够处理无法即时有结果的状态更新并通知状态变更发起者更新结果。
//vuex 的actions定义
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// 逻辑处理
// 在数据变化时发起一个网络请求
this.$http("/api/something").then(response => {
//请求处理正常,将返回结果传入参数
//可以在此执行同步更新vuex的状态值
resolve(response);
}, error => {
// 请求失败,将错误传入参数
reject(error);
})
})
}
}
//vue组件
export default {
mounted: function() {
// 组件创建完成
// 触发vuex的状态值改变,dispatch myAction拿到了vuex的actions中myAction返回的promise实例
this.$store.dispatch("myAction").then(response => {
//在异步操作中的resolve将调用此处代码
}, error => {
//在异步操作中的reject将调用此处代码
})
}
} 5、跨页面传递数据
方法有很多,一种是通过路由的参数传递简单的数据。
this.$route.params.sharedData
VUE是单页应用,页面只是虚拟地在逻辑上跳转,页面本身还是那个页面,所以另外的就是可以通过vuex的状态管理来临时存储数据。
