【问题标题】:Vue/laravel - passing data from blade to vue componentVue/laravel - 将数据从刀片传递到 vue 组件
【发布时间】:2017-02-24 01:11:01
【问题描述】:

我是 Vue 的新手,刚刚学习它,所以我想知道如何修改我拥有的适用于创建表单的组件,我想修改它以便我可以将其用于编辑表单好吧。我需要做的是将图像 src 设置为我从数据库中获得的图像(如果存在)。我怎样才能做到这一点? 这是组件文件:

<template>
<div>
  <div v-if="!image">
    <h2>Select an image</h2>
    <input type="file" @change="onFileChange">
  </div>
  <div v-else>
    <img :src="image" />
    <input type="file" name="image" style="display:none">
    <button @click="removeImage">Remove image</button>
  </div>
</div>
</template>

<script>
export default {
    data() {
        return {
        image: '',
        formData:new FormData(),
        file: null
        }
    },
    methods: {
        onFileChange: function onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createImage(files[0]);
            this.formData.append('file', files[0]);
            this.file = files[0];
        },
        createImage: function createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;
            reader.onload = function (e) {
                vm.image = e.target.result;
            };
            reader.readAsDataURL(file);
        },
        removeImage: function removeImage(e) {
            this.image = '';
        }
    }
}
</script>

在我看来,我已经尝试过这样做:

<image-upload :image="/uploads/{{ $magazine->image }}"></image-upload>

但我得到了错误:

[Vue 警告]:无法编译模板...无效的表达式

更新

我按照答案中的建议做了,并从指令中删除了:,它起作用了,但我现在在控制台中收到一条警告消息:

[Vue 警告]:数据属性“image”已被声明为 prop。 请改用 prop 默认值。 (在组件中找到)

【问题讨论】:

  • 尝试从图像指令中删除:。因为它是一个字符串,所以不需要作为 Javascript 表达式处理。所以&lt;image-upload image="/uploads/{{ $magazine-&gt;image }}"&gt;&lt;/image-upload&gt;
  • 是的,这有帮助!它现在可以工作,但我在控制台中收到一条警告消息,你知道如何摆脱这个:[Vue 警告]:数据属性“图像”已被声明为道具。请改用 prop 默认值。 (在组件 中找到)

标签: laravel vue.js


【解决方案1】:

道具警告是因为您的数据属性中有图像

data() {
    return {
    image: '',
    formData:new FormData(),
    file: null
    }
},

您需要将其从那里移除并将其添加到 props 属性中

props: {
    image: {
        type: String,
        default: ""
    }
},
data() {
    return {
    formData: new FormData(),
    file: null
    }
},

【讨论】:

  • 谢谢!它删除了之前的警告,但现在我有了一个新警告:vue.js?0598:2574 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "image" (found in component &lt;image-upload&gt;)
  • 那是因为您在删除图像中有this.image = ''。如果您有一个数据或计算值,它会在加载时分配给图像道具,然后在内部更新。这会在重新绘制 vue 虚拟 dom 时停止覆盖图像值。
  • 如果没有问题,您能否提供一个代码示例来说明如何做到这一点?因为,目前我无法在更新表单上上传图片。我已经发布了一个关于它的问题here
猜你喜欢
  • 2018-08-24
  • 2021-07-05
  • 2018-10-13
  • 2017-07-27
  • 2021-10-22
  • 2018-06-25
  • 1970-01-01
  • 2021-07-24
  • 2017-02-27
相关资源
最近更新 更多