如何在nuxtjs中使用纯JavaScript?

时间:2019-10-29 10:10:32

标签: nuxt.js

我可以在诸如 index.vue 之类的nuxt页面中使用ECMAScript 2017 javascript 吗?

我必须使用export default吗? 我应该在哪里放置代码?

我发现了如何在文档中使用jsx,但我认为必须有一种使用javascript的简单方法。

https://nuxtjs.org/faq/jsx#how-to-use-jsx-

1 个答案:

答案 0 :(得分:0)

是的,您可以将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>