hooks钩子函数

修改标题

App.vue

<template>
  <div>

  div>
template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import useTitle from '@/hooks/useTitle.js'

// 使用hooks钩子函数
// 返回ref类型的title
const title = useTitle('狗')

// 修改标题,被watch监听到
title.value = '猪'

script>

useTitle.js

import { ref, watch } from 'vue'
export default function (titleName) {
  const title = ref(titleName)

  // 监听title
  watch(title, (newVal) => {
    document.title = newVal
  }, {
    immediate: true
  })

  return title
}

计数器

App.vue

<template>
  <div>
    <h1>{{ count }}h1>
    <button @click="increment">+1button>
    <button @click="decrement">-1button>
  div>
template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import useCounter from './hooks/useCounter.js'

const { count, increment, decrement } = useCounter()

script>

<style scoped>style>

useCounter.js

import { ref } from "vue"
export default function () {
  const count = ref(0)

  function increment() {
    count.value++
  }

  function decrement() {
    count.value--
  }

  return {
    count,
    increment,
    decrement
  }
}

你可能感兴趣的:(vue,javascript,vue.js,开发语言)