mixin 的基本使用

134 阅读1分钟

1.首先定义一个 minix.js 文件,里面写法与 vue 文件中 script 代码完全一致

export default {
  data() {
    // 通用的 table 绑定数据
    tableData: []
  },
  methods: {
    // 通用的数据加载方法
    reloadTable() {
      if (this.url == 'student') {
        this.tableData = [
          {
            date: '2016-05-02',
            name: 'student1',
            address: '上海市普陀区金沙江路 1518 弄'
          },
          {
            date: '2016-05-04',
            name: 'student2',
            address: '上海市普陀区金沙江路 1517 弄'
          }
        ]
      } else if (this.url == 'teacher') {
        this.tableData = [
          {
            date: '2016-05-02',
            name: 'teacher1',
            address: '上海市普陀区金沙江路 1518 弄'
          },
          {
            date: '2016-05-04',
            name: 'teacher2',
            address: '上海市普陀区金沙江路 1517 弄'
          }
        ]
      } else if (this.url == 'manage') {
        this.tableData = [
          {
            date: '2016-05-02',
            name: 'manage1',
            address: '上海市普陀区金沙江路 1518 弄'
          },
          {
            date: '2016-05-04',
            name: 'manage2',
            address: '上海市普陀区金沙江路 1517 弄'
          }
        ]
      }
    }
  }
}

2.mixin 的使用

// 1.导入 mixin 文件
import mixin from '@/components/my-table/table-mixin'

export default {
  components: { MyTable },
  // 2.注册 mixin
  mixins: [mixin],
  
  created() {
  // 3.在需要的地方调用 mixin 中的方法,比如初始化的时候获取表格数据
  this.reloadTable()
},

methods: {
  // 4.角色切换,重新刷新表格
  handleRoleChange(role) {
    this.url = role
    this.reloadTable()
  }
}