Vue 3

December 23, 2019

vue

Vue 3 について

入門

v3 document

Vue エコシステム。以下コンポーネントの beta が外れた時に Vue 3 をプロダクション向けに採用可能になる。

インストール

$ vue create app

状態管理

Vuex を使う方法もあるが、大規模向けということになっている。 Vue3 では provide, inject を使ってコンポーネント間の状態共有が可能

その他

書き方

<template>
  // if
  <div v-if="user.isAdmin">admin</div>
  <div v-else-if="!user.isAdmin">not admin</div>
  <div v-else>not admin</div>

  // loop
  <div v-for="twoot in user.twoots" :key="twoot.id">
    {{ twoot.content }}
  </div>

  <div v-for="(twoot, index) in user.twoots" :key="index">
    {{ twoot.content }}
  </div>

  // event
  <form @submit.prevent="createNewToot">
    <button @click="favoriteTwoot(twoot.id)">submit</button>
  </form>

  // v-model
  <textarea v-model="newTwootContent"></textarea>

  // css js
  <form :class="{ '--exceeded': newTwootWordCount < 180 }"></form>
</template>

<script>
import UserProfile from './components/UserProfile'
// import UserProfile from '@/components/UserProfile'

// Composition API import
import { reactive, computed } from 'vue'

export default {
  // Value
  name: 'App',

  // Reference Components
  components: { UserProfile },

  // Composition API
  setup(props, ctx) {
    const state = reactive{
      newTwootContent: '',
      user: {
        followers: 0,
        isAdmin: true,
        twoots: [
          { id: 1, content: 'あいうえお' },
          { id: 2, content: 'かきくけこ' },
        ],
      },
    }

    const newTwootCharacterCount = computed(() => state.newTwootContent.length)

    function favoriteTwoot(id) {
      // event を 親コンポーネントへ伝える
      ctx.emit('favorite', id)
    }

    function createNewToot() {}

    return {
      state,
      newTwootCharacterCount,
      favoriteTwoot,
      createNewToot
    }
  },

  // Data
  data() {
    return {
      newTwootContent: '',
      user: {
        followers: 0,
        isAdmin: true,
        twoots: [
          { id: 1, content: 'あいうえお' },
          { id: 2, content: 'かきくけこ' },
        ],
      },
    }
  },

  // Lifecycle
  mounted() {},

  watch: {},
  computed: {},
  methods: {
    favoriteTwoot(id) {
      // event を 親コンポーネントへ伝える
      this.$emit('favorite', id)
    },
    createNewToot() {},
  },
}
</script>

// lang, scope style
<style scoped></style>
<style lang="scss" scoped>
.--exceeded: {
  color: red;
}
</style>