如何从 vue.js 上的数据调用方法?
How can I call method from data on vue.js?
我的 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>
如果代码运行,存在这样的错误:
[Vue warn]: Error in data(): "ReferenceError: strSlug is not defined"
如果我console.log(window.location.pathname),结果是这样的:
/store/21/chelsea-hazard-store
因此,如果它与 url 相同且数据在选项卡中,则它将激活
我调用strSlug方法把每个都转成小写,空格转成-
好像不能从数据中调用方法
如何解决错误?
从 vue 对象中访问数据或方法时,使用 this.thing
。在你的情况下,那将是 this.strSlug(this.shop.name)
.
即使使用 'this.' 也不起作用,因为在初始化数据时尚未定义该函数。我认为您必须在 created() 生命周期挂钩中执行此操作。
如果您在 data
中有一个函数将在另一个对象(例如事件处理程序)的上下文中使用,那么 this
将不会指向 Vue 实例。您必须在 data()
:
范围内的另一个变量中保留引用
methods: {
shuffle() {}
},
data() {
var self = this;
return {
onClick: function() {
self.shuffle()
}
}
}
我的 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>
如果代码运行,存在这样的错误:
[Vue warn]: Error in data(): "ReferenceError: strSlug is not defined"
如果我console.log(window.location.pathname),结果是这样的:
/store/21/chelsea-hazard-store
因此,如果它与 url 相同且数据在选项卡中,则它将激活
我调用strSlug方法把每个都转成小写,空格转成-
好像不能从数据中调用方法
如何解决错误?
从 vue 对象中访问数据或方法时,使用 this.thing
。在你的情况下,那将是 this.strSlug(this.shop.name)
.
即使使用 'this.' 也不起作用,因为在初始化数据时尚未定义该函数。我认为您必须在 created() 生命周期挂钩中执行此操作。
如果您在 data
中有一个函数将在另一个对象(例如事件处理程序)的上下文中使用,那么 this
将不会指向 Vue 实例。您必须在 data()
:
methods: {
shuffle() {}
},
data() {
var self = this;
return {
onClick: function() {
self.shuffle()
}
}
}