vue的data中使用this.$route赋值,在this.$options.data()重置的时候报错问的题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue的data中使用this.$route赋值,在this.$options.data()重置的时候报错问的题相关的知识,希望对你有一定的参考价值。

参考技术A 问题

项目里遇到一个问题,用this. data, this.$options.data()); // 有问题!!!
,
methodA ()
// do sth.
,
methodB () // 通过用户操作调用
this.A.a && this.A.a(); // this.A.a is undefined, this.B is undefined!!!



`
调用resetData()之后,再调用methodB()时,this.A.a和this.B是undefined。

解决

resetData里这样写:
resetData () // 更新时调用 Object.assign(this.$data, this.$options.data.call(this));
原因

和Vue实例的初始化相关。(源码version2.6.10)

1、new Vue的时候传了一个对象,把该对象记为options,Vue将options中自定义的属性和Vue构造函数中定义的属性合并为vm. options.data()中的this指向vm. options下,所以this.methodA和this.B为undefined。
`
// 创建一个vue实例
const options =
customOption: 'foo',
data ()
A: this.methodA
,
methods:
methodA ()
,
created: function ()
console.log(this.$options.customOption) // => 'foo'

;
new Vue(options);

// src/core/instance/init.js
initMixin (Vue: Class<Component>)
const vm: Component = this
// ...
vm. options.data映射到vm._data,使得可以通过vm._data访问数据,在映射过程中,通过call将data()的this指向当前的实例vm,并将data()的执行结果返回,因为prop和methods的初始化在data之前,所以这时vm上已有_props和_methods,可以拿到this.methodA和this.B。(vm.key如何实现vm._props.key效果见3)。
`
// src/core/instance/state.js
initState (vm: Component)
// ...
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data)
initData(vm) // 里面通过getData(data, vm)改变this

// ...


getData (data: Function, vm: Component): any
// ...
try
return data.call(vm, vm) // this替换为vm

// ...

3、上面把属性映射到了vm._data里,可以通过vm._data.A访问数据,Vue再通过一个代理方法使得vm.A可以直接访问A。
// src/core/instance/state.js
proxy(vm, _data , key);

proxy (target: Object, sourceKey: string, key: string)
sharedPropertyDefinition.proxyget = function proxyGetter ()
return this[sourceKey][key]

sharedPropertyDefinition.set = function proxySetter (val)
this[sourceKey][key] = val

Object.defineProperty(target, key, sharedPropertyDefinition)

`
总结

data()中若使用了this来访问props或methods,在重置 options.data()的this指向,最好使用this.$options.data.call(this)。

router 和 route

参考技术A 在使用了 vue-router 的应用中,路由对象会被注入到每个组件中,赋值为 $route , 当切换路由时,路由对象会被更新。 this.$route 表示当前的路由对象

3. this.$route.router : 路由规则所属的路由器(以及其所属的组件)

this.$router 包含了很多属性和方法, 任何页面都可以调用。 $router 是一组路由或者说是一种机制,他管理了一组路由 $route 。

* $router 具有如下属性
1. push() 方法: 这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。
字符串 this.$router.push('home')
对象 this.$router.push(path:'home')
命名的路由 this.$router.push(name:'user', params:userId: '123') ==》/这里的 params 不生效

3. forward() 方法,前进一步 this.$router.forward();

4. go() 方法 可前进可后退

this.$router.go(-1) 后退一步
this.$router.go(2) 前进两步,但当步数大于历史记录数,就会无效,是无效,而不是取一个最大值
this.$router.go(0) 会刷新页面

以上是关于vue的data中使用this.$route赋值,在this.$options.data()重置的时候报错问的题的主要内容,如果未能解决你的问题,请参考以下文章

vue中data使用this

vue路由对象($route)参数简介

为啥 vue.js 的 data 中定义的变量不能赋值给对象?

Vue中重置data的数据为初始状态

Vue重置当前页面数据

vue created钩子使用后台数据赋值给data里的变量,报错‘undefined’