将相应的JS文件添加到新的Vue.js组件

时间:2018-01-31 23:49:00

标签: javascript ecmascript-6 vue.js

我正在学习Vue.js并且它到目前为止真的很棒但我在尝试添加另一个JS文件时遇到了问题。我有一个Navigation.vue文件,我试图用它添加一个新的Vue实例到corrsponde,但我没有取得任何成功。

Navigation.js

new Vue({
  el: '#navigation',
  data: {
    active: 'home'
  },
  methods: {
    makeActive: function(item) {
      this.active = item;
    }
  }
});

Navigation.vue

<template>
  <div id="navigation">
    <nav v-bind:class="active" v-on:click.prevent>
        <a href="#" class="home" v-on:click="makeActive('home')">Home</a>
        <a href="#" class="projects" v-on:click="makeActive('projects')">Projects</a>
        <a href="#" class="services" v-on:click="makeActive('services')">Services</a>
        <a href="#" class="contact" v-on:click="makeActive('contact')">Contact</a>
    </nav>
  </div>
</template>

<script>
  export default {
  }
</script>

的application.js

import Vue from "vue/dist/vue.esm"
import App from '../app.vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css';

Vue.use(Vuetify)

document.addEventListener('DOMContentLoaded', () => {
  document.body.appendChild(document.createElement('app'))
  const app = new Vue({
    el: 'app',
    template: '<App/>',
    components: {
      App
    }
  })

  console.log(app)
})

Navigation.js文件不起作用。我认为这是因为我没有正确导入它,但我不确定?

ERROR:

Property or method "active" is not defined on the instance but 
referenced during render. Make sure that this property is reactive, 
either in the data option, or for class-based components, by 
initializing the property

1 个答案:

答案 0 :(得分:3)

我希望您的Navigation组件中包含App组件。

  

App.vue

<template>
  <div>
    <Navigation/>
    <!-- there's probably more than just this -->
  </div>
</template>

<script>
import Navigation from 'path/to/Navigation.vue'

export default {
  // snip
  components: {
    Navigation
  }
  // snip
}
</script>

此外,组件数据应该是一个功能

  

Navigation.vue

<script>
export default {
  data () {
    return { active: 'home' }
  },
  methods: {
    makeActive (item) {
      this.active = item;
    }
  }
}
</script>

您无法为Navigation.js组件添加Vue或单独Navigation个实例