Vue-cli3.0 + Vue 3.0基础使用

Vue 3.0初体验,学习笔记

起手式

  1. 安装vue-cli
    npm install -g @vue/cli
  2. 创建项目
    npm create 项目名
    创建项目时选择 Manually select features ,在选择项目时勾选vue 3.0选项

基础使用

父组件
<template>
  <div class="about">
    <h1>接收子组件的值:{{childValue}}</h1>
    <vueCom :childValue="parentValue" @changeValue='changeValue'></vueCom>
  </div>
</template>

<script>
import vueCom from '../components/Vue3Com.vue'
import { ref } from 'vue'
export default {
  components: {
    vueCom
  },
  setup() {
    let parentValue = ref('父组件的值')
    let childValue = ref()

    let changeValue = (val) => {
      childValue.value = val
    }

    return {
      parentValue,
      childValue,
      changeValue
    }
  }
}
</script>

<style lang="less" scoped>
  h1 {
    color: red
  }
</style>
子组件
<template>
  <div class="vue3Test">
      <div class="textValue">
          <h1>vuex存储的值:{{storeValue}}</h1>
          <h1>count:{{count}}</h1>
          <h1>接收父组件的值:{{parentValue}}</h1>
          <button @click="add" style="margin-right:40px">count++</button>
          <button @click="changeValue">change child value</button>
      </div>
  </div>
</template>

<script>
import { useStore } from 'vuex'
import { computed, ref, watch } from 'vue'
export default {
    // 父组件传值
    props: {
        childValue: {
            type: String,
            default: null
        }
    },
    // 一个组件选项,在组件被创建之前,props 被解析之后执行。组合式 API 的入口
    setup(props, context) {
        // vue 3.0中vuex的使用
        let store = useStore()
        let storeValue = computed(() => store.state.user)

        // 使用父组件的值
        let parentValue = ref(0)
        let changeValue = () => {
            parentValue.value = props.childValue
            context.emit('changeValue', '我是子组件的值')
        }
        
        // 监听变化
        let count = ref(0)
        let add = () => {
            count.value++
        }
        watch(count, (newValue, preValue) => {
            console.log('count发生了变化', newValue, preValue)
        })

        return {
            storeValue,
            count,
            parentValue,
            changeValue,
            add
        }
    }
}

</script>
<style lang='less' scoped>
h1 {
    color: red
}
</style>
结果展示

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值