TaSvet
TaSvet

Reputation: 442

How to set value back to Alpine Variable alpine directive?

I want to make a alpine plugin can be click for select file and return file had select to a variable.

#html
<button x-select="photo">
    <span>Upload</span>
</button>

#script
Alpine.data('UpdateProfile', () => ({
    photo: null,
}));

#alpine directive
Alpine.directive(
    "select",
    (el, { value, expression }, { effect, evaluateLater }) => {
        el.addEventListener("click", (e) => {
            e.preventDefault();
            const input = document.createElement("input");
            input.type = "file";
            input.accept = "*";
            input.addEventListener("change", (e) => {
                const file = e.target.files;
            });
            input.click();
        });
    }
);

How I can set e.target.files to photo alpine variable.

Upvotes: 1

Views: 1063

Answers (1)

Dauros
Dauros

Reputation: 10557

First, you need to create a JS expression, that set the value of the user provided data name to the uploaded file name, then evaluate this expression within the Alpine.js context. For example, if the filename is picture.jpg, then ${expression} = '${file[0].name}' expression becomes photo = 'picture.jpg', so Alpine.js sets photo to the filename.

document.addEventListener('alpine:init', () => {
  Alpine.directive(
    "select",
    (el, { value, expression }, { evaluate }) => {
      el.addEventListener("click", (e) => {
        e.preventDefault()
        const input = document.createElement("input")
        input.type = "file"
        input.accept = "*"
        input.addEventListener("change", (e) => {
          const file = e.target.files
          evaluate(`${expression} = '${file[0].name}'`)
        })
        input.click()
      })
    }
  )
})

Upvotes: 2

Related Questions