javascript 如何从 vue.js 上的数据调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46966689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I call method from data on vue.js?
提问by samuel toh
My vue component like this :
我的 vue 组件是这样的:
<template>
...
<ul class="nav nav-tabs nav-tabs-bg">
<li v-for="tab in tabs" role="presentation" :class="setActive(tab.url)">
<a :href="baseUrl + tab.url">{{tab.title}}</a>
</li>
</ul>
...
</template>
<script>
export default {
props: ['shop'],
data() {
return{
tabs: [
{
title: 'product',
url: '/store/' + this.shop.id + '/' + strSlug(this.shop.name)
},
{
title: 'info',
url: '/store/' + this.shop.id + '/' + strSlug(this.shop.name) + '/info'
}
]
}
},
methods: {
setActive(pathname){
return {active: window.location.pathname == pathname}
},
strSlug: function(val) {
return _.kebabCase(val)
}
}
}
</script>
If the code run, there exist error like this :
如果代码运行,存在这样的错误:
[Vue warn]: Error in data(): "ReferenceError: strSlug is not defined"
[Vue 警告]:data() 中的错误:“ReferenceError:strSlug 未定义”
If I console.log(window.location.pathname), the result like this :
如果我 console.log(window.location.pathname),结果是这样的:
/store/21/chelsea-hazard-store
/store/21/chelsea-hazard-store
So if it is the same as url with data in tabs, then it will active
因此,如果它与标签中的数据的 url 相同,那么它将处于活动状态
I call the strSlug method to convert each into lowercase and convert spaces into -
我调用 strSlug 方法将每个转换为小写并将空格转换为 -
Seems it can not call the method from the data
好像不能从数据中调用方法
How can I solve the error?
我该如何解决错误?
采纳答案by The Guy with The Hat
When accessing data or methods from within the vue object, use this.thing. In your case, that would be this.strSlug(this.shop.name).
从 vue 对象中访问数据或方法时,请使用this.thing. 在您的情况下,那将是this.strSlug(this.shop.name).
回答by gvlasov
If you have a function in datathat will be used in a context of another object (like an event handler, for example), then thiswill not point to the Vue instance. You will have to preserve the reference in another variable from the scope of data():
如果您有一个函数data将在另一个对象的上下文中使用(例如,事件处理程序),则this不会指向 Vue 实例。您必须在以下范围内的另一个变量中保留引用data():
methods: {
shuffle() {}
},
data() {
var self = this;
return {
onClick: function() {
self.shuffle()
}
}
}
回答by Brobic Vripiat
Does not work even with 'this.' because that function has not been defined at the time data is being initialized. I think you have to do it in the created() life-cycle hook.
即使使用“this”也不起作用。因为在初始化数据时尚未定义该函数。我认为您必须在 created() 生命周期挂钩中执行此操作。

