如何从路由器模板调用功能?

时间:2017-08-05 06:52:27

标签: vue.js

我正在使用网址切换进行非常简单的页面。在其中一个网址中,我需要调用@click方法。这是我的代码:

const NotFound = { template: '<p>Page not found</p>' }
const Home = { template: '<p>home page</p>' }
const Faq = { template: '<p>Faq page</p>' }
const Book = { template: `
<div>
    <button @click="foo()">test</button>
</div>
    ` }
const routes = [
  {path: '/', component: Home},
  {path: '/book', component: Book},
  {path: '/faq', component: Faq}
]

const router = new VueRouter({
    routes // short for `routes: routes`
    })

new Vue({
  el: '#app',
  router,
  data: {

  },
  methods: 
  {
    foo()
    {
        console.log("ffffff");
    }
  }
})

但我收到错误:Property or method "foo" is not defined on the instance but referenced during render

1 个答案:

答案 0 :(得分:1)

因为你试图在父组件中定义子组件(书)的方法。请将methods属性从父组件移动到子组件。 这是一个样本。

public class Message
{
  private Mail mail;  
  private Bounce bounce;
  private String notificationType;

  //getter & setters

}
const NotFound = { template: '<p>Page not found</p>' }
const Home = { template: '<p>home page</p>' }
const Faq = { template: '<p>Faq page</p>' }
const Book = { template: `
<div>
    <button @click="foo()">test</button>
</div>
    `
  , methods: // <-- here you go
  {
    foo()
    {
        console.log("ffffff");
    }
  }}
const routes = [
  {path: '/', component: Home},
  {path: '/book', component: Book},
  {path: '/faq', component: Faq}
]

const router = new VueRouter({
    routes // short for `routes: routes`
    })

Vue.use(VueRouter);

new Vue({
  el: '#app',
  router,
  data: {

  }
})