nuxt.js - 如何在 nuxtjs 中使用纯 JavaScript?
问题描述
我可以在像index.vue这样的nuxt 页面中使用 ECMAScript 2017 javascript 吗?
我必须使用export default
吗?我应该把我的代码放在哪里?
我在文档中找到了如何使用 jsx,但我认为必须有一种简单的方法来使用 javascript。
解决方案
是的,您可以将 Vue 单文件组件与普通的旧 javascript 对象一起使用。请参阅https://nuxtjs.org/guide/views#pages上的文档
<template>
<h1 class="red">Hello {{ name }}!</h1>
</template>
<script>
export default {
asyncData (context) {
// called every time before loading the component
// as the name said, it can be async
// Also, the returned object will be merged with your data object
return { name: 'World' }
},
fetch () {
// The `fetch` method is used to fill the store before rendering the page
},
head () {
// Set Meta Tags for this Page
},
// and more functionality to discover
...
}
</script>
<style>
.red {
color: red;
}
</style>
或者您可以将 ES 类与nuxt-class-component
https://github.com/nuxt-community/nuxt-class-component一起使用
<template>
<h1 class="red">Hello {{ name }}!</h1>
</template>
<script>
import Vue from 'vue'
import Component from 'nuxt-class-component'
import {
State,
Getter,
Action,
Mutation,
namespace
} from 'vuex-class'
const Module = namespace('path/to/module')
@Component({
props: {
propMessage: String
}
})
export class MyComp extends Vue {
@State('foo') stateFoo
@State(state => state.bar) stateBar
@Getter('foo') getterFoo
@Action('foo') actionFoo
@Mutation('foo') mutationFoo
@Module.Getter('foo') moduleGetterFoo
@Module.Action('foo') moduleActionFoo
// If the argument is omitted, use the property name
// for each state/getter/action/mutation type
@State foo
@Getter bar
@Action baz
@Mutation qux
// initial data
msg = 123
// use prop values for initial data
helloMsg = 'Hello, ' + this.propMessage
// lifecycle hooks
created () {
this.stateFoo // -> store.state.foo
this.stateBar // -> store.state.bar
this.getterFoo // -> store.getters.foo
this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
this.moduleGetterFoo // -> store.getters['path/to/module/foo']
}
mounted () {
this.greet()
}
fetch () {
// fetch data
}
async asyncData () {
// async fetching data
}
// computed
get computedMsg () {
return 'computed ' + this.msg
}
// method
greet () {
alert('greeting: ' + this.msg)
}
}
</script>
推荐阅读
- apache - 重定向、隐藏文件夹名称并启用具有多个子目录的 URL 访问
- linux - 如何安装翼翼
- python - 创建可共享模块的正确方法(包导入)
- magento - 如何成为更好的 magento 2 开发人员
- tmux - 如何编写 tmux 脚本,使其自动拆分窗口并打开一组文件?
- perl - 如何修复 perl 脚本中“另外使用未初始化的值...”的错误?
- dart - Dart 将 int 变量转换为字符串
- php - 这个“\\1”在php中是什么意思?
- javascript - 在 js 中的对象中分组嵌套数组(Tree Vue.js)
- java - Docker 图像 - 类型。修身vs修身弹力vs弹力vs高山