vue2与vue3使用细节对比

809 阅读2分钟

1 表格数据处理

vue2 表格数据处理 使用是 slot-scope="scope"

     <template slot-scope="scope">
            {{ scope.row.createTime }}
        </template>

vue3 表格数据处理 使用是 #default="scope"

      <template #default="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>

2 数据变量

vue 2中变量

data()函数变量

 return {
     showSearch: true,
       // 总条数
     total: 0, 
    pageSize: 10,
      pageNum: 1,
      queryParams: {
        current: 1,
        size: 10,
        userName: undefined,
        phoneNumber: undefined,
        status: undefined,
        deptId: undefined,
        beginTime: undefined,
        endTime: undefined,
        deptIds: [],
        nickName:undefined,
      },
 }

vue3 中变量

简单的用ref ,赋值一定要用 xx.value,复杂的用 reactive 在配合这个使用toRefs 解构,不使用解构就不要使用value

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
  },
  const total = ref(0)
const { queryParams, preview } = toRefs(data)
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 查询表集合 */
function getList() {
  tableloading.value = true
  listTable(proxy.addDateRange(queryParams.value, dateRange.value)).then((response) => {
    tableList.value = response.data.result
    total.value = response.data.totalNum
    tableloading.value = false
  })
}
/************************************/
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  configName: undefined,
  configKey: undefined,
  configType: undefined,
})

/** 查询参数列表 */
function getList() {
  loading.value = true
  listConfig(proxy.addDateRange(queryParams, dateRange.value)).then((response) => {
    configList.value = response.data.result
    total.value = response.data.totalNum
    loading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/****没有使用this了的nextTick方法*/
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
}


3子组件方法

vue2

    //取消编辑
    sonGoalCancel() {
      this.$emit("sonGoalCancel", this.goalItemIndex, this.actionType);
    },

vue3

const emit = defineEmits(['ok'])
const emit = defineEmits()
function handleSetLineChartData(type) {
  emit('handleSetLineChartData', type)
}

4 elementui 图标方法处理

vue2

<i class="el-icon-share"></i>
 <el-button
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                class="chy-search-searchbtn"
                >搜索
              </el-button>

vue3

       <el-icon>
                <question-filled />
           </el-icon>

 <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>

www.cnblogs.com/bingcola/p/…

5 props 写法

vue2 props 写法

  props: {
	 info: {
        type: Object,
        default: null,
      },
  },

vue3 props写法

const props = defineProps({
  info: {
    type: Object,
    default: null,
  },
})

js知识 blog.csdn.net/weixin_2961…

function isBigEnough(element, index, array) {

return (element >= 10);

}

passed = [12, 5, 8, 130, 44].every(isBigEnough);

//false

passed = [12, 54, 18, 130, 44].every(isBigEnough);

// true

passed = [2, 5, 8, 1, 4].some(isBigEnough);

// false

passed = [12, 5, 8, 1, 4].some(isBigEnough);

// true
————————————————
版权声明:本文为CSDN博主「便利蜂」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_29614359/article/details/113022055

every 需要全部通过 则返回true

some 只需要一个通过则返回true

6 components使用

vue2 components使用

import chyCategoryItem from "../chyTabs/chyComponents/chyCategoryItem";
  components: {
    chyCategoryItem,
  },

vue3 是直接引入 不需要 components

import Editor from '@/components/Editor'

7表单验证方法

vue2表单验证方法

 rules: {
        accessoriesTypeId: [
          { required: true, message: "类型类型不能为空!", trigger: "blur" },
        ],
        accessoriesName: [
          { required: true, message: "类型名称不能为空!", trigger: "blur" },
        ],
        specification: [
          { required: true, message: "规格不能为空!", trigger: "blur" },
        ],
      },
  this.$refs["form"].validate((valid) => {
        if (valid) {
            
        }
  });

vue3表单验证方法

第一种

const data = reactive({
  form: {
    fileUrl: '',
    htmlContent: '',
    toEmails: [
      {
        value: '',
      },
    ],
  },
  rules: {
    subject: [{ required: true, message: '主题不能为空', trigger: 'blur' }],
    content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  },
})

const { form, rules } = toRefs(data)
const { proxy } = getCurrentInstance()
function formSubmit() {
  proxy.$refs['formRef'].validate((valid) => {
    //开启校验
    if (valid) {
      proxy.$modal.loading('loading...')
      var emails = []
      form.value.toEmails.filter((x) => {
        emails.push(x.value)
      })
      var p = {
        ...form.value,
        toUser: emails.toString(),
      }
      // 如果校验通过,请求接口,允许提交表单
      sendEmail(p).then((res) => {
        open.value = false
        if (res.code == 200) {
          proxy.$message.success('发送成功')
          reset()
        }
        proxy.$modal.closeLoading()
      })
      setTimeout(() => {
        proxy.$modal.closeLoading()
      }, 5000)
    } else {
      console.log('未通过')
      //校验不通过
      return false
    }
  })
}

/** 提交按钮 */
function submit() {
  proxy.$refs.userRef.validate((valid) => {
    if (valid) {
      updateUserProfile(props.user).then((response) => {
        proxy.$modal.msgSuccess('修改成功')
      })
    }
  })
}

const formRef = ref()
// 表单重置
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: '0',
  }
  proxy.resetForm('formRef')
}

  <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
</el-form>

第二种 是element-plus 自带的

element-plus.gitee.io/zh-CN/compo…

8 进入页面发起请求

vue2 是 在created或mounted中

vue3 直接在 script中调用

<script setup name="sysmenu">
/** 查询菜单列表 */
function getList() {
  loading.value = true
  listMenu(queryParams.value).then((response) => {
    menuList.value = response.data
    loading.value = false
  })
}    
getList()
proxy.getDicts('sys_normal_disable').then((response) => {
  statusOptions.value = response.data
})
proxy.getDicts('sys_yes_no').then((response) => {
  typeOptions.value = response.data
})
</script>

9删除询问确认

vue2操作是在js里面

  /** 删除按钮操作 */
    handleDelete(row) {
      let selectId = [];
      selectId[0] = row.accessoriesDetailId;
      const accessoriesDetailIds =
        row.accessoriesDetailId == undefined ? this.ids : selectId;
      this.$confirm("确认要删除该配件吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          delAccessoriesDetail(accessoriesDetailIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },

vue3使用组件和js ,代码更简洁

  <el-popconfirm title="确定删除吗?" @onConfirm="handleDelete(scope.row)" style="margin-left:10px">
            <template #reference>
              <el-button type="text" icon="delete" v-hasPermi="['system:article:delete']">删除</el-button>
            </template>
          </el-popconfirm>
/** 删除按钮操作 */
function handleDelete(row) {
  delArticle(row.cid).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('删除成功')
      handleQuery()
    }
  })
}

10 页面跳转

vue2代码

表格里的代码 这个vue3暂时没有找到对应的


        <el-table-column label="服务单号" prop="serviceSellerId">
          <template slot-scope="scope">
            <div class="chy-column">
              <div
                @click="
                  $router.push({
                    name: 'OrderDetail',
                    params: {
                      serviceSellerId: scope.row.serviceSellerId,
                      orderId: scope.row.orderId,
                    },
                  })
                "
                class="chy-column-item itemClor"
              >
                {{ scope.row.serviceSellerId }}
              </div>
            </div>
          </template>
        </el-table-column>

js里的代码

 handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // alert(this.loginForm.rememberMe)
          if (this.loginForm.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), {
              expires: 30
            })
            Cookies.set('rememberMe', this.loginForm.rememberMe, {
              expires: 30
            })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(() => {
              this.loading = false
              // this.getCode()
            })
        }
      })
    },

接收参数代码

  created() {
    this.serviceSellerId = this.$route.params.serviceSellerId;
    this.orderId=this.$route.params.orderId;
  },

vue3代码

import { useRoute, useRouter } from 'vue-router'

const route = useRoute();
const router = useRouter();
const { params, query } = route
const { path } = params

router.replace({ path: '/' + path, query })

router.push({ path: redirect.value || '/' })

/** 新增按钮操作 */
function handleAdd() {
  router.replace({ path: '/article/publish' })
}

/** 删除按钮操作 */
function handleDelete(row) {
  delArticle(row.cid).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('删除成功')
      handleQuery()
    }
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  router.push({ path: '/article/publish', query: { cid: row.cid } })
}
// 详情
function handleView(row) {
  var link = `${previewUrl.value}${row.cid}`
  window.open(link)
}

遗漏知识点:vue路由的跳转之:replace,push和go的区别的区别

blog.csdn.net/weixin_3043…

blog.csdn.net/zhouchuanlu…

跳转操作代码 参考 更多代码写法 以及组件el-dropdown 的用法

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.roleKey != 'admin'">
            <el-button size="small" type="text" icon="edit" @click.stop="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">修改 </el-button>
            <el-button size="small" type="text" icon="delete" @click.stop="handleDelete(scope.row)" v-hasPermi="['system:role:remove']">删除 </el-button>

            <el-dropdown size="small" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit', 'system:role:authorize', 'system:roleusers:list']">
              <span class="el-dropdown-link">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleDataScope" icon="circle-check">菜单权限</el-dropdown-item>
                  <el-dropdown-item command="handleAuthUser" icon="user">分配用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>

js 代码

// 更多操作触发
function handleCommand(command, row) {
  switch (command) {
    case 'handleDataScope':
      handleDataScope(row)
      break
    case 'handleAuthUser':
      handleAuthUser(row)
      break
    default:
      break
  }
}
function handleAuthUser(row) {
  const roleId = row.roleId
  router.push({ path: '/system/roleusers', query: { roleId } })
}

接收参数

const route = useRoute()
const role_id = route.query.roleId

11关于this和页面refs

vue2中使用this

   statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);  
    },
      
    this.msgSuccess("删除成功");
 this.$refs["refSubCat"].getCheckedNodes()[0].pathLabels;
 this.$refs.editModel.deleteFile,

vue3中使用proxy

const { proxy } = getCurrentInstance()

function statusFormat(row, column) {
  return proxy.selectDictLabel(statusOptions.value, row.status)
}
 proxy.$modal.msgSuccess('执行成功')

 proxy.$refs['importRef'].show()
 proxy.$refs["refSubCat"].getCheckedNodes()[0].pathLabels;
 proxy.$refs.editModel.deleteFile,

转换为字符串快捷方法 ——值+''

   if (datas[key].dictValue == ('' + value)) {
      actions.push(datas[key].dictLabel);
      return true;
    }

转化为新的值

   const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))