当我点击标签中的联系人时,这是警告:"属性或方法" switchTo"未在实例上定义,但在呈现期间引用。确保在数据选项中声明反应数据属性。 (在组件中找到)。"
我该如何解决这个问题?
new Vue({
el: '#app',
data: {
currentPage: 'home',
},
methods: {
switchTo: function(page) {
this.currentPage = page;
}
},
components: {
home: {
template: `#home`,
},
about: {
template: `#about`,
},
contact: {
template: '#contact'
}
}
})

.navigation {
margin: 10px 0;
}
.navigation ul {
margin: 0;
padding: 0;
}
.navigation ul li {
display: inline-block;
margin-right: 20px;
}
input, label, button {
display: block
}
input, textarea {
margin-bottom: 10px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app">
<div class="navigation">
<ul>
<li><a href="#home" @click="switchTo('home')">Home</a></li>
<li><a href="#about" @click="switchTo('about')">About</a></li>
</ul>
</div>
<div class="pages">
<keep-alive>
<component v-bind:is="currentPage">
</component>
</keep-alive>
</div>
</div>
<template id="home">
<p>home</p>
</template>
<template id="about">
<p>about <a href="#contact" @click="switchTo('contact')">go to contact</a></p>
</template>
<template id="contact">
<p>contact</p>
</template>
&#13;
答案 0 :(得分:1)
只需将您的about
模板更改为此
<template id="about">
<p>about <a href="#contact" @click="$root.switchTo('contact')">go to contact</a></p>
</template>
new Vue({
el: '#app',
data: {
currentPage: 'home',
},
methods: {
switchTo: function(page) {
this.currentPage = page;
}
},
components: {
home: {
template: `#home`,
},
about: {
template: `#about`,
},
contact: {
template: '#contact'
}
}
})
&#13;
.navigation {
margin: 10px 0;
}
.navigation ul {
margin: 0;
padding: 0;
}
.navigation ul li {
display: inline-block;
margin-right: 20px;
}
input, label, button {
display: block
}
input, textarea {
margin-bottom: 10px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app">
<div class="navigation">
<ul>
<li><a href="#home" @click="switchTo('home')">Home</a></li>
<li><a href="#about" @click="switchTo('about')">About</a></li>
</ul>
</div>
<div class="pages">
<keep-alive>
<component v-bind:is="currentPage">
</component>
</keep-alive>
</div>
</div>
<template id="home">
<p>home</p>
</template>
<template id="about">
<p>about <a href="#contact" @click="$root.switchTo('contact')">go to contact</a></p>
</template>
<template id="contact">
<p>contact</p>
</template>
&#13;
答案 1 :(得分:0)
我已经在这个问题中解决了这样的问题:Calling methods in Vue build
这不是同一个问题,所以这不是一个重复的问题,但答案是一样的:
在创建的钩子中,将组件添加到window.componentInstance,如下所示:
methods: {
foo () {
console.log('bar')
}
},
created () {
window.componentInstance = this
}
然后你可以在任何地方调用这个方法:
window.componentInstance.foo()