Vue @click.native not working?

陌路散爱 提交于 2019-12-06 04:13:07

问题


I have navigation component like this:

<template>
<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="">Website Builder</a>
    </div>
    <div>
        <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav">
                <li>
                    <a href="#" @click.native="currentView='create'">Create</a>
                </li>
                <li>
                    <a href="#" @click.native="currentView='how'">How</a>
                </li>
                <li>
                    <a href="#" @click.native="currentView='about'">About</a>
                </li>
                <li>
                    <a href="#" @click.native="currentView='youtube'">Videos</a>
                </li>
            </ul>
        </div>
    </div>
</nav>
</template>

and my js:

Vue.component('navigation', Navigation)
Vue.component('create', Create)
Vue.component('how', How)
Vue.component('about', About)
Vue.component('youtube', Youtube)

new Vue({
    el: '#app',
    data: {
        currentView: 'create'
    }

and html:

<div id="app">
    <navigation></navigation>
    <keep-alive>
        <transition name="slide-fade" mode="out-in">
            <component :is="currentView"></component>
        </transition>
    </keep-alive>
</div>

However when I click on navigation, it doesn't change therefore I am assuming it's not working properly. if I put navigation away from component and stick it in div id=app it works fine, why is this happening?


回答1:


  1. The .native modifier is not necessary on native elements - it can only be used on component elements. Remove it.

  2. It seems you want to change data in the root component. Your current code changes data in the navigation component.

Two ways to do this:

1) The clean way:

In the navigation component, we emit an event with the new value to the parent:

<a href="#" @click="$emit('current-view', 'youtube')">

in the parent (here, the root) component, we receive the event and set the value:

<navigation @current-view="currentView = $event"></navigation>

2) The hacky way:

<a href="#" @click="$root.currentView='youtube'">


来源:https://stackoverflow.com/questions/47094620/vue-click-native-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!