vue3总结

  1. props

父组件中传递数据给子组件:

<template>
  <ChildComponent :message="parentMessage"/>
</template>

<script>
import ChildComponent from './ChildComponent'

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Hello from parent'
    }
  }
}
</script>

子组件中通过props接收传递过来的数据:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  props: {
    message: String
  }
}
</script>

  1. provide/inject

父组件中提供数据给子组件:

<template>
  <div>
    <child-component></child-component>
  </div>
</template>

<script>
import { provide } from 'vue'
import ChildComponent from './ChildComponent'

export default {
  components: {
    ChildComponent
  },
  setup() {
    const name = 'Jack'
    provide('myName', name)
  }
}
</script>

子组件中通过inject接收数据:

<template>
  <div>{{ myName }}</div>
</template>

<script>
import { inject } from 'vue'

export default {
  setup() {
    const myName = inject('myName')

    return {
      myName
    }
  }
}
</script>

  1. $attrs/$listeners

父组件中传递所有未被props定义的属性和事件给子组件:

<template>
  <ChildComponent class="my-class" @click="handleClick"/>
</template>

<script>
import ChildComponent from './ChildComponent'

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleClick() {
      // handle click event
    }
  }
}
</script>

子组件中可以通过$attrs/$listeners获取所有未被props定义的属性和事件:

<template>
  <div v-bind="$attrs" v-on="$listeners">Hello from child component</div>
</template>

<script>
export default {
  inheritAttrs: false
}
</script>

  1. emit

子组件中触发事件并且传递数据:

<template>
  <button @click="onClick">Click me</button>
</template>

<script>
export default {
  methods: {
    onClick() {
      this.$emit('my-event', 'Hello from child')
    }
  }
}
</script>

父组件中监听事件并且获取传递过来的数据:

<template>
  <div>
    <ChildComponent @my-event="handleEvent"/>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent'

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleEvent(message) {
      console.log(message) // 'Hello from child'
    }
  }
}
</script>

以下是Vue3常用的API及其代码示例:

  1. 创建应用实例
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.mount('#app')

  1. 组件定义
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MyComponent',
  props: {
    propA: String,
    propB: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      msg: 'Hello Vue 3!'
    }
  },
  computed: {
    computedMsg() {
      return this.msg + ' - computed'
    }
  },
  methods: {
    handleClick() {
      console.log('Button clicked!')
    }
  },
  template: `
    <div>
      <p>{{ msg }}</p>
      <p>{{ computedMsg }}</p>
      <button @click="handleClick">Click me!</button>
    </div>
  `
})

  1. ref
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)

    onMounted(() => {
      setInterval(() => {
        count.value++
      }, 1000)
    })

    return {
      count
    }
  }
}

  1. reactive
import { reactive } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
      msg: 'Hello Vue 3!'
    })

    return {
      state
    }
  }
}

  1. watch
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    watch(() => state.count, (newVal, oldVal) => {
      console.log(`Count changed from ${oldVal} to ${newVal}`)
    })

    return {
      state
    }
  }
}

  1. computed
import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    const computedCount = computed(() => state.count * 2)

    return {
      state,
      computedCount
    }
  }
}

  1. 生命周期钩子
import { onMounted, onUpdated, onUnmounted } from 'vue'

export default {
  setup() {
    onMounted(() => {
      console.log('Component mounted!')
    })

    onUpdated(() => {
      console.log('Component updated!')
    })

    onUnmounted(() => {
      console.log('Component unmounted!')
    })
  }
}

以上是Vue3常用的API及其代码示例。

        

        计算属性是Vue.js中的一个重要概念,用于简化模板中复杂表达式的计算过程。在Vue3中,计算属性的使用方式与Vue2相同,但有些细节上的变化,下面给出一个Vue3的计算属性总结:

<template>
  <div>
    <p>原始数据:{{message}}</p>
    <p>计算属性:{{computedMessage}}</p>
    <p>计算属性getter和setter:{{fullName}}, 修改后: <input v-model="fullName"></p>
  </div>
</template>

<script>
import { computed, reactive } from 'vue'

export default {
  setup() {
    const state = reactive({
      firstName: 'John',
      lastName: 'Doe'
    })

    // 计算属性
    const computedMessage = computed(() => {
      return `Hello ${state.firstName} ${state.lastName}`
    })

    // 计算属性的getter和setter
    const fullName = computed({
      get() {
        return `${state.firstName} ${state.lastName}`
      },
      set(val) {
        const names = val.split(' ')
        state.firstName = names[0]
        state.lastName = names[names.length - 1]
      }
    })

    return {
      message: 'Hello Vue 3!',
      computedMessage,
      fullName
    }
  }
}
</script>

上述代码中,我们通过 reactive 函数创建了一个响应式状态对象 state,其中包含了 firstNamelastName 两个属性。接着,我们使用 computed 函数定义了两个计算属性 computedMessagefullNamecomputedMessage 是一个只有 getter 的简单计算属性,它根据 state 中的 firstNamelastName 属性计算出一个新的字符串。fullName 是一个有 gettersetter 的计算属性,它可以被修改,并将输入的字符串解析成 firstNamelastName 两个属性,并更新 state 对象。

在模板中,我们通过双花括号语法({{ }})引用了这些计算属性,展示了它们的值。注意,在计算属性的getter和setter中,我们使用了对象字面量的方式来定义计算属性,同时设置了 getset 方法。

需要注意的是,在Vue3中,我们使用了 import { computed, reactive } from 'vue' 来导入Vue3中的 computedreactive 函数。另外,在setup函数中,我们返回了 messagecomputedMessagefullName 三个变量,这些变量可以在模板中使用。

Vue3 中提供了 watch API 来监听响应式数据的变化,并且可以执行相应的逻辑。同时,还有 watchEffect API 可以监听数据变化并执行一些副作用,类似于 Vue2 中的 computed

下面是 watchwatchEffect 的代码块总结:

  1. 使用 watch 监听数据变化
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    watch(
      () => state.count, // 监听的变量或表达式
      (newVal, oldVal) => {
        console.log(`count changed from ${oldVal} to ${newVal}`)
      }
    )

    return {
      state // 返回响应式对象
    }
  }
}

  1. 使用 watch 监听多个响应式数据变化
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      count1: 0,
      count2: 0
    })

    watch(
      [() => state.count1, () => state.count2], // 监听的多个变量或表达式
      ([newVal1, newVal2], [oldVal1, oldVal2]) => {
        console.log(`count1 changed from ${oldVal1} to ${newVal1}`)
        console.log(`count2 changed from ${oldVal2} to ${newVal2}`)
      }
    )

    return {
      state
    }
  }
}

  1. 使用 watch 监听嵌套响应式数据变化
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      a: {
        b: {
          c: 0
        }
      }
    })

    watch(
      () => state.a.b.c,
      (newVal, oldVal) => {
        console.log(`c changed from ${oldVal} to ${newVal}`)
      }
    )

    return {
      state
    }
  }
}

  1. 使用 watchEffect 监听数据变化并执行副作用
import { reactive, watchEffect } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    watchEffect(() => {
      console.log(`count changed to ${state.count}`)
    })

    return {
      state
    }
  }
}

  1. 使用 watchEffect 监听多个响应式数据变化并执行副作用
import { reactive, watchEffect } from 'vue'

export default {
  setup() {
    const state = reactive({
      count1: 0,
      count2: 0
    })

    watchEffect(() => {
      console.log(`count1 changed to ${state.count1}`)
      console.log(`count2 changed to ${state.count2}`)
    })

    return {
      state
    }
  }
}

以上就是 Vue3 中监听和监听副作用的总结。

以下是使用 Vue3 官方提供的 createApp 方法创建根实例的代码块示例:

import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);
app.mount('#app');

这个示例中,createApp 方法用于创建一个根实例 app,并将 App 组件作为根组件传入。接着使用 app.mount('#app') 方法将应用挂载到页面中的 idapp 的 DOM 元素上。以上代码实现了 Vue3 的初始化及挂载过程。

值得一提的是,Vue3 中使用 createApp 方法代替了 Vue2 中的 Vue 构造函数,这也是 Vue3 与 Vue2 的一个重要区别。

vue3与vue2的区别
  1. Composition API

Vue 3 引入了 Composition API,它是一种新的组件写法,与 Vue 2 的 Options API 不同,Composition API 更加灵活和高效。 Composition API 是一种基于函数的 API,通过提供一组功能强大的函数来组合我们的逻辑,让我们可以更好地逻辑复用和代码组织。

Vue 2 Options API 示例:

export default {
  data() {
    return {
      count: 0,
      message: 'Hello World!'
    }
  },
  methods: {
    greet() {
      alert(this.message)
    },
    increment() {
      this.count++
    }
  }
}

Vue 3 Composition API 示例:

import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
      message: 'Hello World!'
    })

    const greet = () => {
      alert(state.message)
    }

    const increment = () => {
      state.count++
    }

    const double = computed(() => {
      return state.count * 2
    })

    return { state, greet, increment, double }
  }
}

  1. Fragment

Vue 3 的模板支持了 Fragment,可以同时返回多个根节点,而不需要使用额外的 div 或者 template 标签来包裹。

Vue 2 示例:

<template>
  <div>
    <h1>Header</h1>
    <p>Content</p>
    <footer>Footer</footer>
  </div>
</template>

Vue 3 示例:

<template>
  <>
    <h1>Header</h1>
    <p>Content</p>
    <footer>Footer</footer>
  </>
</template>

  1. Teleport

Vue 3 引入了 Teleport,可以帮助我们更方便地将组件渲染到目标元素之外,而不需要使用特殊的 CSS 或 JavaScript。

Vue 2 示例:

<template>
  <div>
    <button @click="showModal">Show Modal</button>
    <div v-if="show">
      <h2>Modal</h2>
      <p>This is a modal.</p>
    </div>
  </div>
</template>

Vue 3 示例:

<template>
  <div>
    <button @click="showModal">Show Modal</button>
    <teleport to="body" v-if="show">
      <div>
        <h2>Modal</h2>
        <p>This is a modal.</p>
      </div>
    </teleport>
  </div>
</template>

  1. Suspense

Vue 3 引入了 Suspense,它可以帮助我们更优雅地处理异步组件加载和渲染。

Vue 2 示例:

<template>
  <div>
    <h1>{{ post.title }}</h1>
    <p>{{ post.content }}</p>
    <div v-if="loading">Loading...</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      post: null,
      loading: true
    }
  },
  mounted() {
    this.fetchPost()
  },
  methods: {
    fetchPost() {
      axios.get('/api/post/1')
        .then(response => {
          this.post = response.data
          this.loading = false
        })
    }
  }
}
</script>

Vue 3 示例:

<template>
  <div>
    <h1>{{ post.title }}</h1>
    <p>{{ post.content }}</p>
    <Suspense>
      <template #fallback>
        <div>Loading...</div>
      </template>
      <Comments :postId="post.id" />
    </Suspense>
  </div>
</template>

<script>
import { defineAsyncComponent, Suspense } from 'vue'

const Comments = defineAsyncComponent(() => import('./Comments.vue'))

export default {
  data() {
    return {
      post: null
    }
  },
  mounted() {
    this.fetchPost()
  },
  methods: {
    fetchPost() {
      axios.get('/api/post/1')
        .then(response => {
          this.post = response.data
        })
    }
  }
}
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值