Vue component set data value of child

泄露秘密 提交于 2019-12-24 00:12:13

问题


I am using vue carousel

https://ssense.github.io/vue-carousel/api/

It woks well but I need to resetthe carousel

I can see there is a value of current page and I think setting this to 0 would work as a reset. However these seems to be no exposed method to allow me to do this. Can I set it from the parent?


回答1:


If you want to set a data property on a child component, you can set a ref attribute on that child's tag and then access the child instance via this.$refs.


In your case, you could add a ref to the carousel tag like so:

<Carousel ref="carousel"/>

And then in you parent component's script, you can set the currentPage property of the child component like so:

this.$refs.carousel.currentPage = 0;



回答2:


For reset purpose, another solution will be:

  1. bind :key to data property for VueCarousel

  2. when 'reset' event is triggered, just change data property to new value like below demo (data property=resetIndex).

Because When :key is changed to new one, it will re-mount the component.

const buildSlideMarkup = (count) => {
	let slideMarkup = '';
  for (var i = 1; i <= count; i++) {
  	slideMarkup += '<slide><span class="label">' + i + '</span></slide>'
  }
  return slideMarkup;
};

new Vue({
	el: '#example',
  components: {
  	'carousel': VueCarousel.Carousel,
    'slide': VueCarousel.Slide
  },
  data() {
  	return {
    	resetIndex: 1
    }
  },
  methods: {
  	reset: function () {
    	this.resetIndex += 1
    }
  },
  template: '<div><button @click="reset()">Reset</button><carousel :key="resetIndex" :scrollPerPage="false">' + buildSlideMarkup(10) + '</carousel></div>'
});
.VueCarousel-slide {
  position: relative;
  background: #42b983;
  color: #fff;
  font-family: Arial;
  font-size: 24px;
  text-align: center;
  min-height: 100px;
}

.label {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://ssense.github.io/vue-carousel/js/vue-carousel.min.js"></script>

<div id="example"></div>


来源:https://stackoverflow.com/questions/51674312/vue-component-set-data-value-of-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!