vue extend运用

216 阅读1分钟

vue extend运用

组件
import {Button} from "ant-design-vue"
import Vue from "vue"
const MyComponet = Vue.extend({
  props: ["outState", "increase"],
  data() {
    return {
      innerState: 0,
    };
  },
  render() {
    return (
      <div style="border-bottom:1px solid #ddd;">
        <h2>inner component</h2>
        <div style="margin: 10px 0;">
          inner: { this.innerState }; out: { this.outState.count };<br/>
          <Button style="margin-right: 10px;" onClick={() => { this.innerState++ }}>Increase Inside</Button>
          <Button onClick={ this.increase }>Increase</Button>
        </div>
      </div>
    );
  },
});

运用

export default {
  name: 'eChild',
  data() {
    return {
      state: {
        count: 0,
      },
    };
  },
  methods: {
    addComponent() {
      let target = this.$refs.myElement;
      let source = new MyComponet({
        propsData: {
          outState: this.state,
          increase: () => {
            this.state.count++;
          },
        },
      }).$mount();
      target.appendChild(source.$el);
    }
  },
  render() {
    return (
      <div>
        <h1>outCount: {this.state.count}</h1>
        <div ref="myElement" style="margin-bottom: 10px;"></div>
        <Button style="margin-right: 10px;" onClick={ this.addComponent }>Add</Button>
        <Button style="margin-right: 10px;" onClick={() => { this.state.count++ }}>Increase</Button>
        <Button onClick={() => { this.state.count-- }}>Decrease</Button>
      </div>
    )
  }
};

注意使用render函数页面不能使用template,否则会渲染失败