gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:59:08 26 4
gpt4 key购买 nike

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

导航.js

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

导航.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>

应用程序.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 文件不工作。我认为这是因为我没有正确导入它,但我不确定?

错误:

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

最佳答案

我希望看到的是您的 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 组件无需包含 Navigation.js 或单独的 Vue 实例

关于javascript - 将相应的 JS 文件添加到新的 Vue.js 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com