最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3?使用setup語法糖實現(xiàn)分類管理功能

 更新時間:2022年08月18日 15:14:21   作者:Holyzq  
這篇文章主要介紹了vue3?使用setup語法糖實現(xiàn)分類管理,本次模塊使用 vue3+element-plus 實現(xiàn)一個新聞?wù)镜暮笈_分類管理模塊,其中新增、編輯采用對話框方式公用一個表單,需要的朋友可以參考下

setup語法糖簡介

直接在 script 標簽中添加 setup 屬性就可以直接使用 setup 語法糖了。

使用 setup 語法糖后,不用寫 setup 函數(shù),組件只需要引入不需要注冊,屬性和方法也不需要再返回,可以直接在 template 模板中使用。

setup語法糖中新增的api

  • defineProps:子組件接收父組件中傳來的 props
  • defineEmits:子組件調(diào)用父組件中的方法
  • defineExpose:子組件暴露屬性,可以在父組件中拿到

模塊簡介

本次模塊使用 vue3+element-plus 實現(xiàn)一個新聞?wù)镜暮笈_分類管理模塊,其中新增、編輯采用對話框方式公用一個表單。

分類模塊路由

添加分類模塊的路由

import { createRouter, createWebHistory } from "vue-router";
import Layout from "@/views/layout/IndexView";

const routes = [
  {
    path: "/sign_in",
    component: () => import("@/views/auth/SignIn"),
    meta: { title: "登錄" },
  },
  {
    path: "/",
    component: Layout,
    children: [
      {
        path: "",
        component: () => import("@/views/HomeView"),
        meta: { title: "首頁" },
      },
      // 分類管理
      {
        path: "/categories",
        component: () => import("@/views/categories/ListView"),
        meta: { title: "分類列表" },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

分類列表組件

views/categories/ListView.vue

<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首頁</el-breadcrumb-item>
      <el-breadcrumb-item>內(nèi)容管理</el-breadcrumb-item>
      <el-breadcrumb-item>分類列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider />

    <el-button type="primary">新增</el-button>

    <el-table :data="categories" style="width: 100%" class="set-top">
      <el-table-column prop="id" label="編號" width="180" />
      <el-table-column label="名稱" width="180">
        <template #default="scope">
          <el-tag>{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="180">
        <template #default="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column label="創(chuàng)建日期" width="180">
        <template #default="scope">
          {{ formatter(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >編輯
          </el-button>
          <el-popconfirm
            title="確定要刪除么?"
            confirm-button-text="確定"
            cancel-button-text="取消"
            @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button size="small" type="danger">刪除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

獲取分類列表數(shù)據(jù)

<script setup>
  import { ref } from "vue"; // 5、導(dǎo)入 ref
  import { fetchCategoryList } from "@/api/categories"; // 6、導(dǎo)入接口 api
  import moment from "moment"; // 7、導(dǎo)入 moment 包
  import { ElMessage, ElNotification } from "element-plus"; // 9、導(dǎo)入消息通知包
  
  // 4、定義分類列表數(shù)組
  const categories = ref([]);

  // 1、獲取分類列表數(shù)據(jù)
  const init = async () => {
      const res = await fetchCategoryList();
      // 3、賦值
      categories.value = res.data.categories;
  };

  // 2、調(diào)用 init 方法
  init();

  // 8、時間格式化
  const formatter = (date) => {
      if (!date) {
        return "";
      }
      moment.locale("zh-cn");
      return moment(date).format("LL");
  };

  const handleEdit = (row) => {
    console.log(row);
  };
  
  // 10、點擊刪除按鈕
  const handleDelete = (row) => {
      try {
          const res = await deleteCategory(row.id);
          if (res.code === 20000) {
              init();
              ElNotification({
                  title: "成功",
                  message: res.message,
                  type: "success",
              });
          }
      } catch (e) {
          if (e.Error) {
            ElMessage.error(e.Error);
          }
      }
  };
</script>

分類表單組件

1、新建 src/views/categories/components/CategoryForm.vue

<template>
  <el-dialog v-model="dialogFormVisible" title="新增分類">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="名稱" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" size="large" />
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
        <el-input v-model.number="form.sort" autocomplete="off" size="large" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">立即創(chuàng)建</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
  import { reactive, ref } from "vue";

  // 1、定義對話框?qū)傩?,默認值為 false
  const dialogFormVisible = ref(false);

  // 2、定義表單對象和屬性
  const form = ref({
    name: "",
    sort: 0,
  });
  
  const formLabelWidth = "140px";

  // 3、表單驗證
  const ruleFormRef = ref();
  const rules = reactive({
    name: [
      { required: true, message: "請輸入分類名稱", trigger: "blur" },
      { min: 2, max: 20, message: "長度在 2 ~ 20 位", trigger: "blur" },
    ],
    sort: [
      { required: true, message: "請輸入排序", trigger: "blur" },
      { type: "number", message: "排序必須為數(shù)字值" },
    ],
  });
  
  // 4、表單提交
  const submitForm = async (formEl) => {
    await formEl.validate(async (valid) => {
      if (valid) {
        console.log('submit');
      }
    }
  } 
</script>

2、在 categories/ListView.vue 中引入上述表單組件

<template>
  <div>
    .
    .
    <!--表單對話框-->
    <CategoryForm ref="dialogShow" />
  </div>
</template>

<script setup>
  import CategoryForm from "./components/CategoryForm"; // 導(dǎo)入對話框組件
</script>

ref=“dialogShow”:給表單對話框起別名

3、給新增、編輯按鈕分別綁定事件,點擊后彈出對話框

<el-button type="primary" @click="handleCreate">新增</el-button>

<el-button size="small" @click="handleEdit(scope.row)">編輯</el-button>
// 點擊新增按鈕觸發(fā)子組件的 showForm 方法,并傳參 create,代表新增
const dialogShow = ref(null);
const handleCreate = async () => {
  dialogShow.value.showForm("create");
};

// 點擊編輯按鈕鈕觸發(fā)子組件的 showForm 方法,并傳參 edit 和編輯所需的 id 值,代表編輯
const handleEdit = async (row) => {
  dialogShow.value.showForm("edit", { id: row.id });
};

4、在表單組件中

<script setup>
  // 顯示對話框
  const showForm = async (type, data) => {
    console.log(type);
    console.log(data);
  }
</script>  

測試:此時點擊新增或編輯按鈕,發(fā)現(xiàn)無法觸發(fā) showForm 方法。原因在于我們要在父組件中調(diào)用子組件的方法,需導(dǎo)出子組件的方法后才能調(diào)用

<script setup>
  import { defineExpose } from "vue";

  defineExpose({
    showForm,
  });
</script>

此時再次點擊新增或編輯按鈕,發(fā)現(xiàn)已經(jīng)拿到了 type 和 data 的值了。

5、完成新增和編輯的對話框正常顯示

// 定義表單類型的默認值為 create
const formType = ref("create");

// 完成新增和編輯正常對話框顯示
const showForm = async (type, data) => {
  dialogFormVisible.value = true;
  formType.value = type;
  if (type == "create") {
    form.value = {};
  } else {
    fetchCategory(data.id).then((res) => {
      form.value = res.data.category;
    });
  }
};

對話框字體顯示

根據(jù) formType 的值判斷顯示新增或編輯

<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="formType == 'create' ? '新增分類' : '編輯分類'"
  >
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="名稱" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" size="large" />
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
        <el-input v-model.number="form.sort" autocomplete="off" size="large" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">{{
          formType == "create" ? "立即創(chuàng)建" : "立即更新"
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

完成新增和編輯功能

import {
  createCategory,
  fetchCategory,
  updateCategory,
} from "@/api/categories";
import { ElMessage, ElNotification } from "element-plus";

// 表單提交
const submitForm = async (formEl) => {
  await formEl.validate(async (valid) => {
    if (valid) {
      let res;
      try {
        if (formType.value == "create") {
          res = await createCategory(form.value);
        } else {
          res = await updateCategory(form.value.id, form.value);
        }
        if (res.code === 20000) {
          ElNotification({
            title: "成功",
            message: res.message,
            type: "success",
          });
          dialogFormVisible.value = false;
        }
      } catch (e) {
        if (e.Error) {
          ElMessage.error(e.Error);
        }
      }
    }
  });
};

當(dāng)新增或編輯表單提交后,新的數(shù)據(jù)要同步渲染到頁面,根據(jù)思路,我們需要調(diào)用父組件的 init 方法即可,所以這里涉及到子組件調(diào)用父組件的方法

修改父組件引用子組件的代碼,增加 @init 事件,綁定 init 方法

<!--表單對話框-->
<CategoryForm ref="dialogShow" @init="init" />

在子組件中調(diào)用,注意注釋中的代碼

// eslint-disable-next-line no-undef
const emit = defineEmits(["init"]); // 引入父組件的 init 方法
const submitForm = async (formEl) => {
  await formEl.validate(async (valid) => {
    if (valid) {
      let res;
      try {
        if (formType.value == "create") {
          res = await createCategory(form.value);
        } else {
          res = await updateCategory(form.value.id, form.value);
        }
        if (res.code === 20000) {
          ElNotification({
            title: "成功",
            message: res.message,
            type: "success",
          });
          dialogFormVisible.value = false;
          emit("init"); // 調(diào)用 init
        }
      } catch (e) {
        if (e.Error) {
          ElMessage.error(e.Error);
        }
      }
    }
  });
};

到此這篇關(guān)于vue3 使用setup語法糖實現(xiàn)分類管理的文章就介紹到這了,更多相關(guān)vue3 setup語法糖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 自定義vue組件發(fā)布到npm的方法

    自定義vue組件發(fā)布到npm的方法

    本篇文章主要介紹了自定義vue組件發(fā)布到npm的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Vue?+?element-ui?背景圖片設(shè)置方式

    Vue?+?element-ui?背景圖片設(shè)置方式

    這篇文章主要介紹了Vue?+?element-ui?背景圖片設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • 微信內(nèi)置開發(fā) iOS修改鍵盤換行為搜索的解決方案

    微信內(nèi)置開發(fā) iOS修改鍵盤換行為搜索的解決方案

    今天小編就為大家分享一篇微信內(nèi)置開發(fā) iOS修改鍵盤換行為搜索的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • 全面總結(jié)Vue3.0的多種偵聽方式

    全面總結(jié)Vue3.0的多種偵聽方式

    Vue提供了一種更通用的方式來觀察和響應(yīng)當(dāng)前活動的實例上的數(shù)據(jù)變動:偵聽屬性,下面這篇文章主要給大家介紹了關(guān)于Vue3.0多種偵聽方式的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • vue2組件實現(xiàn)懶加載淺析

    vue2組件實現(xiàn)懶加載淺析

    本篇文章主要介紹了vue2組件實現(xiàn)懶加載淺析,運用懶加載則可以將頁面進行劃分,需要的時候加載頁面,可以有效的分擔(dān)首頁所承擔(dān)的加載壓力.
    2017-03-03
  • Vue router錯誤跳轉(zhuǎn)到首頁("/")的問題及解決

    Vue router錯誤跳轉(zhuǎn)到首頁("/")的問題及解決

    這篇文章主要介紹了Vue router錯誤跳轉(zhuǎn)到首頁("/")的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • 封裝Vue Element的table表格組件的示例詳解

    封裝Vue Element的table表格組件的示例詳解

    這篇文章主要介紹了封裝Vue Element的table表格組件的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2020-08-08
  • vue+iview使用樹形控件的具體使用

    vue+iview使用樹形控件的具體使用

    這篇文章主要介紹了vue+iview使用樹形控件的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • vue中v-model動態(tài)生成的實例詳解

    vue中v-model動態(tài)生成的實例詳解

    這篇文章主要介紹了vue中v-model動態(tài)生成的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解掌握這部分內(nèi)容,需要的朋友可以參考下
    2017-10-10
  • Vue.use源碼學(xué)習(xí)小結(jié)

    Vue.use源碼學(xué)習(xí)小結(jié)

    這篇文章主要介紹了Vue.use源碼學(xué)習(xí)小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06

最新評論

璧山县| 汉寿县| 建宁县| 东乡| 鹤壁市| 隆林| 定南县| 蓝田县| 玉环县| 仁怀市| 嘉峪关市| 于都县| 清丰县| 云梦县| 开远市| 淳化县| 和平区| 齐齐哈尔市| 宜州市| 涟源市| 桃源县| 广水市| 云和县| 涞水县| 壶关县| 务川| 治多县| 镇巴县| 玛多县| 南岸区| 麻城市| 密山市| 定州市| 丰都县| 鄂伦春自治旗| 广德县| 霞浦县| 英吉沙县| 乌审旗| 宁强县| 上杭县|