我一直在遵循创建vue-router对象的指南,但浏览器显示以下警告:
[Vue警告]:未定义属性或方法“auth_login” 实例,但在渲染期间引用。确保声明被动 数据选项中的数据属性。 (在匿名组件中找到 - 使用“name”选项可以更好地调试消息。)
我刚在html标签上添加了一个事件绑定,如下所示:
<div id="app">
<router-view>
</router-view>
<script type="text/temptlate" id="t_auth">
<div class="auth">
<router-view></router-view>
</div>
</script>
<script type="text/temptlate" id="t_auth_login">
<div class="auth_login">
<div>
<button class="btn-primary full" id="btn_login" @click="auth_login" @keyup.enter="auth_login">登录</button>
</div>
</div>
</script>
</div>
JS代码是:
(function() {
let getView = (id) => {
tmp = document.getElementById(id)
if (tmp == null) {
return null;
}
return tmp.innerHTML
};
const routes = [{
path: '/auth',
component: { template: getView('t_auth') },
children: [
{ path: 'register', component: { template: getView('t_auth_register') } },
]
}];
const router = new VueRouter({
routes: routes
});
const app = new Vue({
router: router,
el: "#app",
data: {
name: 'Vue.js'
},
// 在 `methods` 对象中定义方法
methods: {
auth_login: function(event) {
// 方法内 `this` 指向 vm
alert('Hello ' + this.name + '!')
}
}
}).$mount('#app')
})();
为什么找不到auth_login
方法呢?生命周期怎么样?
如何在模板中绑定事件?
完整的源代码位于:https://github.com/295421489/reminder-ximu/tree/dev/public
答案 0 :(得分:1)
我对您的问题没有直接的答案,但这是您调试Vue应用程序的方法:
在Google Chrome浏览器中安装https://github.com/vuejs/vue-devtools。您可能需要重新启动浏览器以使扩展程序开始工作。 (我不记得我是如何第一次拿到它的)
一旦你拥有Vue开发工具,只要加载Vue应用程序(Vue.js的开发版本),你就会在开发者控制台中看到这个:
您的路线也会很好地显示出来。正如您所看到的,我上面的应用当前位于路线/chapter/1
(左侧的橙色框)
点击“发送到控制台”,您的开发者控制台中将显示$vm
实例。
在这里,您可以找到适用于您的路线的auth_login
方法。您还可以为您的应用程序进行更多调试。
如果你想要一个有效的Vue应用程序(有路线)进行测试,你会在这个答案中找到一个jsFiddle:https://stackoverflow.com/a/40215123/654825
希望它有所帮助!
答案 1 :(得分:1)
我解决了这个问题。
错误是找不到方法,我认为是因为范围。所以,我首先创建了一个组件:
var t_auth_login = Vue.extend({
template: getView('t_auth_login'),
// 在 `methods` 对象中定义方法
methods: {
auth_login: function(event) {
}
});
,路线值为:
const routes = [{
path: '/auth',
component: t_auth}]
一切都很好。