2017-08-05 35 views
0

我正在做網頁切換非常簡單的頁面。在我需要調用@click方法的url之一。這裏是我的代碼:如何從路由器模板調用功能?

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

因爲您正試圖在父組件中定義子組件(書)的方法。請將方法屬性從父組件移至子組件。 下面是一個示例。

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: { 
 

 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.7.0/vue-router.min.js"></script> 
 
<div id="app"> 
 
    <router-link :to="{ path: '/' }">Home</router-link> 
 
    <router-link :to="{ path: '/faq' }">FAQ</router-link> 
 
    <router-link :to="{ path: '/book' }">book</router-link> 
 
    <router-view></router-view> 
 
</div>