首页 > 解决方案 > 如何在 nuxtjs 中使用纯 JavaScript?

问题描述

我可以在像index.vue这样的nuxt 页面中使用 ECMAScript 2017 javascript 吗?

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

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

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

标签: nuxt.js

解决方案


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


推荐阅读