Vue on click inside component

时间:2017-10-30 15:31:28

标签: vue.js vuejs2 vue-component

I have component like this:

<template>
<!-- Content for section1 -->
<div id="section1" class="container-fluid home-div">
    <h1 class="text-center">Create Your own Website!</h1>
    <p>Welcome to website builder a place where magic comes true. This website will allow you to create your own website, host it on our webserver and change the content or add content as you go!
    </p>
    <button v-on:click="next" class="btn btn-primary"></button>
</div>
</template>

and my js:

  import Vue from 'vue';
import VueRouter from 'vue-router';
import Section1 from '../vue/components/homepage.vue';
import Section2 from '../vue/components/section2.vue';

const routes = [
    { path: '/', component: Section1 },
    { path: '/about', components: Section2, },
];

Vue.use(VueRouter);

const router = new VueRouter({
    routes,
});

new Vue({
    el: '#homepage',
    router,
});

html:

<div id="homepage">
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="{{ url('template') }}">Website Builder</a>
        </div>
        <div>
            <div class="collapse navbar-collapse" id="myNavbar">
                <ul class="nav navbar-nav">
                    <li><router-link to="/">Create</router-link></li>
                    <li><router-link to="about">How</router-link></li>
                </ul>
            </div>
        </div>
    </nav>
    <router-view></router-view>
</div>

So now when I click on the link nothing happens, it has a path of /#/ and /#/about respectively, and are being transformed to tags, what is wrong with my current code? Should the navigation be as a template maybe or within the template?

2 个答案:

答案 0 :(得分:2)

您的组件具有本地范围,这意味着它将尝试在组件本身上调用next方法,而不是在您实际定义方法的根实例上调用。

根据您的具体情况和需要,您需要在homepagesection2组件中移动方法。

或者,只要在子组件中调用click事件,您就需要通知您的根Vue实例。 Vue.js可以为child-parent通信提供许多通信模式,这很简单:

https://vuejs.org/v2/guide/components.html#Custom-Events

点击后,您将emit来自您的子组件的事件,并使用v-on收听根实例中的事件。

但从它的外观来看,你想要实现每页一个组件的路由:

https://vuejs.org/v2/guide/routing.html

答案 1 :(得分:0)

在您的“新应用”中,当您设置“&#39; el&#39;属性应该引用html元素的ID(根元素)。

你的html应该是这样的:

<div id="homepage">
  <homepage v-if="seen"></homepage>
  <section2 v-else></section2>
</div>